三值的排序 Sorting a Three-Valued Sequence(洛谷 P1459USACO2.1,IOI96Day2)

Sorting a Three-Valued Sequence

IOI'96 - Day 2
Sorting is one of the most frequently performed computational tasks. Consider the special sorting problem in which the records to be sorted have at most three different key values. This happens for instance when we sort medalists of a competition according to medal value, that is, gold medalists come first, followed by silver, and bronze medalists come last.

In this task the possible key values are the integers 1, 2 and 3. The required sorting order is non-decreasing. However, sorting has to be accomplished by a sequence of exchange operations. An exchange operation, defined by two position numbers p and q, exchanges the elements in positions p and q.

You are given a sequence of key values. Write a program that computes the minimal number of exchange operations that are necessary to make the sequence sorted.

本来打了贪心得进行模拟,后来改成了如下玄学贪心做法,十分简洁。欢迎Hack。
统计1,2,3的个数,可知放置1,2,3正确的位置,统计在各位置的数字1,2和3的个数,具体详见下。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;

const int MAXN=1000+5;
int ct[4],c[4][4];
int a[MAXN];

int main()
{
	freopen("sort3.in","r",stdin);
	freopen("sort3.out","w",stdout);
	int n;
	scanf("%d",&n);
	for(int i=1;i<=n;++i)
		scanf("%d",&a[i]),++ct[a[i]];
	for(int i=1;i<=ct[1];++i)
		++c[1][a[i]];
	for(int i=ct[1]+1;i<=ct[1]+ct[2];++i)
		++c[2][a[i]];
    //统计个数
	int ans=0;
	ans+=c[1][2]+c[1][3];//把1换到正确位置的最少步数
	c[2][3]+=max(0,c[2][1]-c[1][2]);//有多少3被交换到了二位置
	ans+=c[2][3];//将2,3交换到正确位置
	printf("%d\n",ans);
	return 0;
}
posted @ 2017-10-20 20:33  chwhc  阅读(179)  评论(0编辑  收藏  举报