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.
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
讲道理,就是贪心好不好。
根据排序后的位置贪心就好了。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <set>
#include <queue>
#include <algorithm>
#include <vector>
#include <cstdlib>
#include <cmath>
#include <ctime>
#include <stack>
#define INF 2100000000
#define ll long long
#define clr(x) memset(x,0,sizeof(x))
using namespace std;
const int N = 1050;
int n,sum,cnt,cnt1,l;
int a[N],b[N],v[4],V[4];
template <class T> inline void read(T &x)
{
x = 0;
int flag = 1;
char ch = (char)getchar();
while(ch<'0' || ch>'9')
{
if(ch=='-') flag = -1;
ch = (char)getchar();
}
while(ch>='0' && ch<='9')
{
x = (x<<1) + (x<<3) + ch-'0';
ch = (char)getchar();
}
x *= flag;
}
int main()
{
freopen("sort3.in","r",stdin);
freopen("sort3.out","w",stdout);
read(n);
for(int i = 1; i <= n; i++)
read(a[i]), b[i] = a[i], v[a[i]]++;
sort(a+1, a+n+1);
l = v[1]+v[2];
for(int i = 1; i <= l; i++)
{
if(b[i] == 1) V[1]++;
else if(b[i] == 2) V[2]++;
else sum++;
}
V[1] = v[1]-V[1];
V[2] = v[2]-V[2];
for(int i = 1; i <= l; i++)
{
if(b[i] == 3 && --V[1])
b[i] = 1;
else if(b[i] == 3) b[i] = 2;
}
for(int i = 1; i <= l; i++)
if(b[i] == 1 && b[i] != a[i]) sum++;
printf("%d\n",sum);
return 0;
}