hdu 5122 K.Bro Sorting

http://acm.hdu.edu.cn/showproblem.php?pid=5122

题意:就是经过几个回合可以使得序列变成有序的,求回合数。

思路:数状数组。倒着插入,每次求和,判断在这个数前面是不是有数,只要有数就ans++;最后插入完,ans就是答案。

 1 #include <cstdio>

 2 #include <cstring>

 3 #include <algorithm>

 4 #define maxn 1000100

 5 using namespace std;

 6 

 7 int t,n;

 8 int c[maxn];

 9 int a[maxn];

10 

11 int lowbit(int x)

12 {

13     return x&-x;

14 }

15 

16 void insert(int x,int y)

17 {

18     while(x<maxn)

19     {

20         c[x]+=y;

21         x+=lowbit(x);

22     }

23 }

24 

25 int Getsum(int x)

26 {

27     int ans=0;

28     while(x>0)

29     {

30         ans+=c[x];

31         x-=lowbit(x);

32     }

33     return ans;

34 }

35 int main()

36 {

37       scanf("%d",&t);

38       for(int cas=1; cas<=t; cas++)

39       {

40           memset(c,0,sizeof(c));

41           memset(a,0,sizeof(a));

42           scanf("%d",&n);

43           for(int i=0; i<n; i++)

44           {

45               scanf("%d",&a[i]);

46           }

47           int ans=0;

48           for(int i=n-1; i>=0; i--)

49           {

50               int xx=Getsum(a[i]-1);

51               if(xx!=0)

52               ans++;

53               insert(a[i],1);

54           }

55           printf("Case #%d: %d\n",cas,ans);

56       }

57       return 0;

58 }
View Code

 

你可能感兴趣的:(sort)