【poj3270】 Cow Sorting
http://poj.org/problem?id=3270 (题目链接)
题意
n个数要要按从小到大的顺序排列,每次只能交换任意两个数,交换的代价为这两个数之和,问最小代价。
Solution
题目简单,想清楚再写。。而我想清楚已经过去15分钟了→_→
细节
如果Wa了请点开Discuss,里面有组hack数据。
代码
// poj3270 #include<algorithm> #include<iostream> #include<cstdlib> #include<cstring> #include<cstdio> #include<cmath> #define LL long long #define inf 1<<30 #define Pi acos(-1.0) #define free(a) freopen(a".in","r",stdin),freopen(a".out","w",stdout); using namespace std; const int maxn=10010,maxm=100010; int a[maxn],b[maxn],t[maxm],num[maxn]; int vis[maxn]; int n; int main() { scanf("%d",&n); for (int i=1;i<=n;i++) scanf("%d",&a[i]),b[i]=a[i]; sort(b+1,b+1+n); for (int i=1;i<=n;i++) t[b[i]]=i; for (int i=1;i<=n;i++) num[i]=t[a[i]]; LL ans=0; for (int i=1;i<=n;i++) if (!vis[i]) { int cnt=0,tmp=0; for (int j=i;!vis[j];j=num[j]) vis[j]=1,tmp+=a[j],cnt++; ans+=tmp+min(b[i]*(cnt-2),b[1]*(cnt+1)+b[i]); } printf("%lld",ans); return 0; }
This passage is made by MashiroSky.