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 requiredSAMPLE 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;
}