第十四届华中科技大学程序设计竞赛 F Sorting Trees

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

题目描述

It’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 and K as described above.
Then the next line are N integers indicating the unsorted 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=0||k>n的话 就不用进行冒泡了,遍历一遍,如果k=1的话 肯定是-1。

#include<string.h>
#include<algorithm>
#include<stdio.h>
using namespace std;
const int maxn=1e5+10;
int n,k;
long long num[maxn],num1[maxn];
int main(){
	int i,j;
	scanf("%d%d",&n,&k);
	for(i=1;i<=n;i++){
		scanf("%lld",&num[i]);
		num1[i]=num[i];
	}
	sort(num1+1,num1+n+1);
	if(k==1){
		printf("-1\n");
		return 0;
	}
	else if(k==0||k>=n){
		int flag=0;
		for(i=1;i<=n;i++){
			if(num1[i]!=num[i]){
				printf("%d\n",i);
				flag=1;
				break;
			}
		}
		if(!flag)	printf("-1\n");
		return 0;
	}
	int tot=1;
	for(i=1;i<n;i++){
		for(j=n;j-k>=1;j--)
			if(num[j-k]>num[j])swap(num[j-k],num[j]);
		if(num1[tot]!=num[tot]){
			break;
		} 
		tot++;
	}
	if(tot!=n)
		printf("%d\n",tot);
	else
		printf("-1\n");
	return 0;
}

2

猜你喜欢

转载自blog.csdn.net/bao___zi/article/details/80148738