bzoj 1697: [Usaco2007 Feb]Cow Sorting[Permutation Group]

I still don't know what a permutation group is... What the solution says is what it
is.jpg The following is from hzwer: http://hzwer.com/3905.html

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
const int N=10005;
int n,w[N],a[N],v[N];
struct qwe
{
    int x,id;
}b[N];
bool cmp(const qwe &a,const qwe &b)
{
    return a.x<b.x;
}
int read()
{
    int r=0,f=1;
    char p=getchar();
    while(p>'9'||p<'0')
    {
        if(p=='-')
            f=-1;
        p=getchar();
    }
    while(p>='0'&&p<='9')
    {
        r=r*10+p-48;
        p=getchar();
    }
    return r*f;
}
int main()
{
    n=read();
    for(int i=1;i<=n;i++)
        w[i]=b[i].x=read(),b[i].id=i;
    sort(b+1,b+1+n,cmp);
    for(int i=1;i<=n;i++)
        a[b[i].id]=i;
    int ans=0;
    for(int i=1;i<=n;i++)
        if(!v[i])
        {
            int s=1,p=i,mn=w[i],sum=w[i];
            v[i]=1;
            while(!v[a[p]])
                p=a[p],v[p]=1,mn=min(mn,w[p]),sum+=w[p],s++;
            ans+=min(sum+mn*(s-2),mn+sum+b[1].x*(s+1));
        }
    printf("%d\n",ans);
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325312242&siteId=291194637