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

USACO [2.1] Sorting a Three-Valued Sequence

2015-12-09 17:27 495 查看
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 sortedhave at most three different key values. This happens for instancewhen we sort medalists of a competition according
to medal value, thatis, gold medalists come first, followed by silver, and bronze medalistscome 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 tobe accomplished by a sequence of exchange operations. An exchangeoperation, defined by two position numbers p and q, exchanges
the elementsin positions p and q.

You are given a sequence of key values. Write a program that computesthe minimal number of exchange operations that are necessary to makethe sequence sorted.

PROGRAM NAME: sort3

INPUT FORMAT

Line 1:N (1 <= N <= 1000), the number ofrecords 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

一开始思路错误导致wa了几次。。
wa思路:类似冒泡排序,直接查找,对2正向找小于它的数,对3逆向找小于它的数。很明显这样子会导致一些应该和2交换的数变成了和3交换

AC思路:先统计出每个数字的数量划分三个区域,在三个区域中分别查找需要交换的数字。在区域1中同样要符合数字2要正向找,数字3逆向找

然后在区域2统计一下3的数量就行。

下面是代码:

/*
ID: shhyzzu
PROG: sort3
LANG: C++
*/
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>
#include<queue>
#include<cmath>
#include<iomanip>
using namespace std;
int n;
int a[2000];
int num[5]={};
int ans=0;
void init()
{
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
num[a[i]]++;
}
}
void work()
{
for(int i=1;i<=num[1];i++)
{
if(a[i]==2)
{
for(int j=num[1]+1;j<=n;j++)//正向查找1
{
if(a[j]==1)
{
int t=a[i];
a[i]=a[j];
a[j]=t;
ans++;
break;
}
}
}
else if(a[i]==3)
{
for(int j=n;j>num[1];j--)//逆向查找1
{
if(a[j]==1)
{
int t=a[i];
a[i]=a[j];
a[j]=t;
ans++;
break;
}
}
}
}
for(int i=num[1]+1;i<=num[1]+num[2];i++)
{
if(a[i]==3)//统计区域2中3的数量
ans++;
}
printf("%d\n",ans);
}
int main()
{
freopen("sort3.in","r",stdin);
freopen("sort3.out","w",stdout);
init();
work();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: