您的位置:首页 > 产品设计 > UI/UE

[USACO2.1]三值的排序 Sorting a Three-Valued Sequence

2017-06-16 21:10 549 查看
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.

PROGRAM NAME: sort3

INPUT FORMAT

Line 1:N (1 <= N <= 1000), the number of records to be sorted
Lines 2-N+1:A single integer from the set {1, 2, 3}

SAMPLE INPUT (file sort3.in)

9
2
2
1
3
3
3
2
3
1

OUTPUT FORMAT

A single line containing the number of exchanges required

SAMPLE OUTPUT (file sort3.out)

4


Sorting a Three-Valued Sequence三值的排序

IOI'96 - Day 2


目录

 [隐藏
1 描述
2 格式
3 SAMPLE
INPUT
4 SAMPLE
OUTPUT


[编辑]描述

排序是一种很频繁的计算任务。现在考虑最多只有三值的排序问题。一个实际的例子是,当我们给某项竞赛的优胜者按金银铜牌排序的时候。在这个任务中可能的值只有三种1,2和3。我们用交换的方法把他排成升序的。

写一个程序计算出,给定的一个1,2,3组成的数字序列,排成升序所需的最少交换次数。


[编辑]格式

PROGRAM NAME: sort3

INPUT FORMAT:

(file sort3.in)

第一行:

奖牌个数N (1 <= N <= 1000)

第 2行到第N+1行:

每行一个数字,表示奖牌。共N行。(1..3)

OUTPUT FORMAT:

(file sort3.out)

共一行,一个数字。表示排成升序所需的最少交换次数。


[编辑]SAMPLE
INPUT

9
2
2
1
3
3
3
2
3
1


[编辑]SAMPLE
OUTPUT

4


【题解】

姿势在下面~

/*
ID:luojiny1
LANG:C++
TASK:sort3
*/
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn=1010;
int main()
{
freopen("sort3.in","r",stdin);
freopen("sort3.out","w",stdout);
int ar[maxn];//输入位置
int br[maxn];//正确位置
int csum=0;//错位的数的个数
int c[4][4]={0};//c[i][j]表示应该是i但是(输入中)变成了j的个数
int n,ans=0;
scanf("%d",&n);
for(int i=0;i<n;i++)
{
scanf("%d",&ar[i]);
br[i]=ar[i];
}
sort(br,br+n);
for(int i=0;i<n;i++)
if(br[i]!=ar[i])
{
c[br[i]][ar[i]]++;
csum++;
}

for(int i=1;i<=3;i++)
for(int j=1;j<=3;j++)
if(i!=j)
{
//当i->j j->i 可以直接互换的时候ans+1
int t=min(c[i][j],c[j][i]); //取最小的错位个数
c[i][j]-=t;
c[j][i]-=t;
csum-=2*t;
ans+=t;
}
ans+=csum/3*2;//剩下的一定是i->j j->k k->i /3是因为i、j、k三数,都是需要耗费两次

printf("%d\n",ans);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: