现在的位置: 首页 > 综合 > 正文

POJ 3270 置换群定理

2018年01月20日 ⁄ 综合 ⁄ 共 2298字 ⁄ 字号 评论关闭

 

Cow Sorting
Time Limit: 2000MS   Memory Limit: 65536K
Total Submissions: 4078   Accepted: 1442

Description

Farmer John's N (1 ≤ N ≤ 10,000) cows are lined up to be milked in the evening. Each cow has a unique "grumpiness" level in the range 1...100,000. Since grumpy cows are more likely to damage FJ's milking equipment, FJ would like to reorder
the cows in line so they are lined up in increasing order of grumpiness. During this process, the places of any two cows (not necessarily adjacent) can be interchanged. Since grumpy cows are harder to move, it takes FJ a total of
X+Y units of time to exchange two cows whose grumpiness levels are
X and Y.

Please help FJ calculate the minimal time required to reorder the cows.

Input

Line 1: A single integer: N.
Lines 2..N+1: Each line contains a single integer: line i+1 describes the grumpiness of cow
i.

Output

Line 1: A single line with the minimal time required to reorder the cows in increasing order of grumpiness.

Sample Input

3
2
3
1

Sample Output

7

Hint

2 3 1 : Initial order.
2 1 3 : After interchanging cows with grumpiness 3 and 1 (time=1+3=4).
1 2 3 : After interchanging cows with grumpiness 1 and 2 (time=2+1=3).

Source

 
这个题我很早就交过了。
昨天有个人问我做法。我又去翻了一下。卧槽,一看我才知道,原来以前又不知道是在哪儿copy的代码。。(鄙视自己一下。。)
然后就很囧的在看了下题目,先开始没有什么思路,然后看了下discuss,发现是一个置换群的题目,于是按照置换群的思路想了下,发现用置换群还比较合理。
于是就动手敲了下。
由于模拟能力一直很弱,所以中间涉及到数组下标交换什么的,在草稿纸上画了很久才理清楚。
写好之后提交居然WA了
在看了下discuss,发现原来还有种特殊情况,就是用全局最小的值去喝每一个群置换。
加上这种情况再次提交就过掉了。。
 
太弱了,弱爆了。。啊啊啊啊啊。。
 
我的代码:
#include<stdio.h>
#include<vector>
#include<algorithm>

using namespace std;

struct node
{
	int level;
	int data;
};
node cow[10005];
vector<int>group[10005];
int a[10005],b[10005];
bool flag[10005];

bool cmp(node x,node y)
{
	return x.data<y.data;
}

int min(int a,int b)
{
	if(a>b)
		return b;
	else
		return a;
}

int main()
{
	int n,i,j,G,temp,nb;
	while(scanf("%d",&n)!=EOF)
	{
		nb=9999999;
		for(i=1;i<=n;i++)
		{
			scanf("%d",&cow[i].data);
			cow[i].level=i;
			if(cow[i].data<nb)
				nb=cow[i].data;
		}
		stable_sort(cow+1,cow+1+n,cmp);
		memset(flag,0,sizeof(flag));
		for(i=1;i<=n;i++)
		{
			a[cow[i].level]=i;
			b[cow[i].level]=cow[i].data;
			group[i].clear();
			G=0;
		}
		for(i=1;i<=n;i++)
		{
			if(!flag[i])
			{
				G++,temp=i;
				group[G].push_back(i);
				flag[i]=true;
				while(true)
				{
					temp=a[temp];
					if(flag[temp])
						break;
					group[G].push_back(temp);
					flag[temp]=true;
				}
			}
		}
		int ans=0;
		for(i=1;i<=G;i++)
		{
			int g=group[i].size(),sum1=0,l=0,tmp[10005],sum2=0;
			for(j=0;j<g;j++)
				tmp[l++]=b[group[i][j]];
			sort(tmp,tmp+l);
			for(j=1;j<l;j++)
				sum1=sum1+tmp[j]+tmp[0];
			sum2=sum2+2*(tmp[0]+nb);
			for(j=1;j<l;j++)
				sum2=sum2+tmp[j]+nb;
			ans=ans+min(sum1,sum2);
		}
		printf("%d\n",ans);
	}
	return 0;
}

抱歉!评论已关闭.