2018 华中科技大学校赛 F Sorting Trees

时间:2021-05-23 14:57:20

链接:https://www.nowcoder.com/acm/contest/106/F
来源:牛客网

t’s universally acknowledged that there’re innumerable trees in the campus of HUST.

One day the tree manager of HUST asked you to sort N trees increasing by their heights a i. Because you were a warm-hearted and professional programmer, you immediately wrote the  Bubble Sort to finish the task. However, you were so tired that made a huge mistake:
for(int i=1;i<n;i++)
    for(int j=1;j<=n-i;j++)
         if(a[j+k]<a[j])swap(a[j+k],a[j]);
Usually k=1 is the normal  Bubble Sort. But you didn't type it correctly. When you now realize it, the trees have been replanted. In order to fix them you must find the first place that goes wrong, compared with the correctly sorted tree sequence.

If every trees are in their correct places then print -1. And you should know k can be equal to 1 which means you didn't make any mistake at all. Also you don't need to consider the part j+k beyond n.

输入描述:



The first line contains two integers N 2018 华中科技大学校赛 F Sorting Trees and K 2018 华中科技大学校赛 F Sorting Trees as described above.
Then the next line are N integers indicating the unsorted trees. 2018 华中科技大学校赛 F Sorting Trees

输出描述:A integer in a single line, indicating the first place that goes wrong. Or -1 means no mistake.

示例1

输入

5 2

2 3 1 4 5

输出

2

等差数列 K为公差,k决定了哪些位置上的数可以比较大小

#include<bits/stdc++.h>
#define maxn 100010
#define INF 0x3f3f3f3f3f3f3f3f
#define ll long long
using namespace std;
int main()
{
	ll n,k,a[maxn],b[maxn];
	cin>>n>>k;
	for(int i=0;i<n;i++)
	{
		cin>>a[i];
		b[i]=a[i];
	}
	sort(b,b+n);
	map<ll,ll> m;
	for(int i=0;i<n;i++)
	{
		m[b[i]]=i;
	}
	ll ans=INF;
	if(k!=0)
	{
		for(int i=0;i<n;i++)
		{
			if(abs(m[a[i]]-i)%k)
			{
				ans=min(m[a[i]]+1,ans);
			}
		}
		if(ans==INF)
			ans=-1;
	}
	else
	{

		for(int i=0;i<n;i++)
		{
			if(a[i]!=b[i])
			{
				ans=i+1;
				break;
			}
		}
		if(ans==INF)
			ans=-1;
	}

	cout<<ans<<endl;
	return 0;
}