hdu1394
The inversion number of a given number sequence a1, a2, ..., an is the number of pairs (ai, aj) that satisfy i < j and ai > aj.
For a given sequence of numbers a1, a2, ..., an, if we move the first m >= 0 numbers to the end of the seqence, we will obtain another sequence. There are totally n such sequences as the following:
a1, a2, ..., an-1, an (where m = 0 - the initial seqence)
a2, a3, ..., an, a1 (where m = 1)
a3, a4, ..., an, a1, a2 (where m = 2)
...
an, a1, a2, ..., an-1 (where m = n-1)
You are asked to write a program to find the minimum inversion number out of the above sequences.
Input
The input consists of a number of test cases. Each case consists of two lines: the first line contains a positive integer n (n <= 5000); the next line contains a permutation of the n integers from 0 to n-1.
Output
For each case, output the minimum inversion number on a single line.
Sample Input
10
1 3 6 9 0 8 5 7 4 2
Sample Output
16
-----------AC----------------
虽然数据只有5000,但暴力会超时
注意一点:当第p[i]个数据跑到最后面时,总数应该先减去这个a[i]的逆序数,sum-num[i],然后这个a[i]排到最后面,即加上除了p[i]外比p[i]大的数目,n-num[i]-1,即总数sum=sum-num[i]+(n-num[i]-1)
模拟一下例题
1 2 3 4 5 6 7 8 9 10
p[i] 1 3 6 9 0 8 5 7 4 2
num[i] 1 2 4 6 0 4 2 2 1 0
sum=22
当p[1]排到后面,更新num[i],每个比p[1]大的都加一,sum=sum-num[i]+(n-num[i]-1)
1 2 3 4 5 6 7 8 9 10
p[i] 3 6 9 0 8 5 7 4 2 1
num[i] 3 5 7 0 5 3 3 2 1 0
sum=29
1 #include<iostream> 2 #include<cstring> 3 #include<cmath> 4 #include<cstdio> 5 #include<algorithm> 6 using namespace std; 7 #define MAXN 5010 8 #define INF 999999999 9 int main() 10 { 11 int n; 12 while(cin>>n) 13 { 14 int p[MAXN],sum = 0,num[MAXN]; 15 int i,j; 16 for(i = 0; i < n; ++i) 17 cin>>p[i]; 18 memset(num,0,sizeof(num)); 19 for(i = 0; i < n-1; ++i) 20 { 21 for(j = i; j < n; ++j) 22 if(p[i] > p[j]) 23 num[i]++; 24 sum += num[i]; 25 cout<<num[i]<<" "; 26 } 27 int t = sum; 28 for(i = 0; i< n-1; ++i) 29 { 30 t = t - num[i] + (n-num[i]-1); 31 sum = min(sum,t); 32 // cout<<t<<endl; 33 //更新num[i]值 34 for(j = i+1; j<n; ++j) 35 if(p[j] >p [i]) 36 num[j] ++; 37 } 38 cout<<sum<<endl; 39 } 40 return 0; 41 }
现在所有的不幸都是以前不努力造成的。。。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· 用 C# 插值字符串处理器写一个 sscanf
· Java 中堆内存和栈内存上的数据分布和特点
· 开发中对象命名的一点思考
· .NET Core内存结构体系(Windows环境)底层原理浅谈
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· DeepSeek 解答了困扰我五年的技术问题。时代确实变了!
· 本地部署DeepSeek后,没有好看的交互界面怎么行!
· 趁着过年的时候手搓了一个低代码框架
· 推荐一个DeepSeek 大模型的免费 API 项目!兼容OpenAI接口!