HUST 1347 Reverse Number(归并排序)

Reverse Number

Time Limit: 1 Sec   Memory Limit: 128 MB
Submissions: 357   Solved: 66

Description

Given a non-negative integer sequence A with length N, you can exchange two adjacent numbers each time. After K exchanging operations, what’s the minimum reverse number the sequence can achieve?

The reverse number of a sequence is the number of pairs (i, j) such that 
i < j and Ai > Aj

Input

There are multiple cases.
For each case, first line contains two numbers: N, K
2<=N<=100000, 0 <= K < 2^60
Second line contains N non-negative numbers, each of which not greater than 2^30

Output

Minimum reverse number you can get after K exchanging operations.

Sample Input

3 1
3 2 1
5 2
5 1 4 3 2

Sample Output

Case #1: 2
Case #2: 5


题目大意:每一次只能交换相邻的两个数字,问经过k次交换以后能够得到的最短的非递增序列
传说中的归并排序
View Code
 1 #include <stdio.h>
 2 #include <string.h>
 3 #include <string.h>
 4 int a[110000],c[110000];
 5 int n;
 6 long long cnt,k;
 7 void mergesort(int l,int r)
 8 {
 9     int mid,i,j,tmp,q;
10     if (r>l+1)
11     {
12         mid=(l+r)/2;
13         mergesort(l,mid-1);
14         mergesort(mid,r);
15         tmp=l;
16         i=l;j=mid;
17         while (i<mid&&j<=r)
18         {
19             if (a[i]>a[j])
20             {
21                 c[tmp++]=a[j++];
22                 cnt+=mid-i;
23             }
24             else c[tmp++]=a[i++];
25         }
26         if (j<=r)
27         {
28             for ( ;j<=r;++j)
29                 c[tmp++]=a[j];
30         }
31         else 
32         {
33             for (;i<mid;++i) c[tmp++]=a[i];
34         }
35         for (i=l;i<=r;++i)
36             a[i]=c[i];
37     }
38     else if (r-l==1&&a[r]<a[l]) {cnt++;q=a[r];a[r]=a[l];a[l]=q;}
39     return;
40 }
41 int main()
42 {
43     bool flag;
44     int i,j,l,m,q,w,e,r;
45     r=0;
46     while (scanf("%d%lld",&n,&k)!=EOF)
47     {
48         r++;
49         cnt=0;
50         for (i=1;i<=n;i++)
51             scanf("%d",&a[i]);
52         mergesort(1,n);
53         cnt=cnt-k;
54         flag=false;
55         for (i=1;i<=n-1;i++)
56             if (a[i]==a[i+1]) flag=true;
57             if (cnt<0) 
58             {
59                 if((-cnt)%2==0||flag)cnt=0;else cnt=1;
60             }
61             printf("Case #%d: %lld\n",r,cnt);
62     }
63     return 0;
64 }

 

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值