置换群的第二题,一开始总是tle,后来一思考,置换根本不是这个情况,置换是一种排列,就用了几个数组将输入的数进行操作,最后A了,对置换有一些了解了。
#include<cstdio> #include<cstring> #include<algorithm> using namespace std; const int maxn = 10000+10; int n,least; int a[maxn],b[1000010],s[maxn],tmp[1000010]; void solve() { int num,sum=0,cnt=1; memset(b,0,sizeof(b)); memset(tmp,0,sizeof(tmp)); sort(s+1,s+1+n); for(int i=1; i<=n; i++) { tmp[s[i]]=a[cnt++]; } for(int k=1; k<=n ; k++) { int count=0,cnt_sum=0; if(b[s[k]]==1) continue; num=s[k]; int minn=100000000; do { num=tmp[num]; b[num]=1; cnt_sum+=num; if(minn>num) minn=num; count++; } while(num!=s[k]); int ok1=(count-2)*minn+cnt_sum; int ok2=(count+1)*least+minn+cnt_sum; sum+=min(ok1,ok2); } printf("%d\n",sum); } int main() { while(~scanf("%d",&n)) { memset(s,0,sizeof(s)); least=1000000000; for(int i=1; i<=n; i++) { scanf("%d",&a[i]); least=min(least,a[i]); s[i]=a[i]; } solve(); } return 0; } /* 5 1 8 5 6 4 */
原文地址:http://blog.csdn.net/zh9406/article/details/45203177