[ 题解 ] [ 排序 ] A. Out of Sorts

http://codeforces.com/group/NVaJtLaLjS/contest/238202/problem/A


题意:

一个冒泡排序,每循环一轮,输出一次moo

对于给出的N个数据,问排序完会输出几个moo


示例:

Input

5
1
5
3
8
2

Output

4


非常明显,这就是在问冒泡排序需要多少次循环才能完成排序。

我抄了题目的伪代码提交超时了,N最高10,0000个数据,冒泡效率极低。


这就需要你总结出冒泡排序的特点了。这是示例的数据:

1 5 3 8 2
1 3 5 2 8
1 3 2 5 8
1 2 3 5 8


对于一个从0到N-2检查的冒泡,一个数据如2,每经过一轮循环,它就往前移动一次;

那么对于排序前和排序后的元素,只要检查一个数据往前移动的最大次数,就可以得到答案。


注意,已经排序好的数据,这个冒泡也会检查一遍后才退出,会多出一次moo


代码如下:

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 
 4 int N;
 5 struct Node
 6 {
 7     int local,value;
 8 }A[100002]={0};
 9 int answer=0 ;
10 
11 int compare(const void *a,const void *b)
12 {
13     struct Node *p1=(struct Node*)a,*p2=(struct Node*)b;
14     if(p1->value==p2->value)return (p1->local) - (p2->local) ;
15     return (p1->value) - (p2->value) ;
16 }
17 
18 int max(int a,int b)
19 {
20     if(a>b)return a;
21     else return b;
22 }
23 
24 int main()
25 {
26     scanf("%d",&N);
27     for(int n=0;n<N;n++)
28     {
29         scanf("%d",&A[n].value);
30         A[n].local=n;
31     }
32     qsort(A,N,sizeof(struct Node),compare);
33     
34 //    for(int n=0;n<N;n++)
35 //        printf("%d,%d\n",A[n].local,A[n].value);
36     
37     for(int n=0;n<N;n++)
38         if(A[n].local > n)
39             answer=max(answer,A[n].local-n);
40     
41     printf("%d\n",answer+1);
42     return 0;
43 }


posted @ 2019-03-15 15:08  Kaidora  阅读(166)  评论(0编辑  收藏  举报