一 原题
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 requiredSAMPLE OUTPUT (file sort3.out)
4
二 分析
三 代码
USER: Qi Shen [maxkibb3] TASK: sort3 LANG: C++ Compiling... Compile: OK Executing... Test 1: TEST OK [0.000 secs, 4184 KB] Test 2: TEST OK [0.000 secs, 4184 KB] Test 3: TEST OK [0.000 secs, 4184 KB] Test 4: TEST OK [0.000 secs, 4184 KB] Test 5: TEST OK [0.000 secs, 4184 KB] Test 6: TEST OK [0.000 secs, 4184 KB] Test 7: TEST OK [0.000 secs, 4184 KB] Test 8: TEST OK [0.000 secs, 4184 KB] All tests OK.
Your program ('sort3') produced all correct answers! This is your submission #2 for this problem. Congratulations!
/*
ID:maxkibb3
LANG:C++
PROG:sort3
*/
#include<cstdio>
int n;
int a[1005];
int cnt[3];
int b[3][3];
int max(int a, int b) {
return (a<b)?b:a;
}
int main() {
freopen("sort3.in", "r", stdin);
freopen("sort3.out", "w", stdout);
scanf("%d", &n);
for(int i = 0; i < n; i++) {
scanf("%d", &a[i]);
cnt[a[i] - 1]++;
}
for(int i = 0; i < cnt[0]; i++) {
b[0][a[i] - 1]++;
}
for(int i = cnt[0]; i < cnt[0] + cnt[1]; i++) {
b[1][a[i] - 1]++;
}
for(int i = cnt[0] + cnt[1]; i < n; i++) {
b[2][a[i] - 1]++;
}
int ans = b[0][1] + b[0][2] +
b[1][2] + max(b[1][0], b[0][1]) - b[0][1];
printf("%d\n", ans);
return 0;
}

本文介绍了一种专门针对仅有三个不同键值(1、2、3)的特殊序列排序问题,通过交换操作达到非递减排序的目标,并提供了一个C++实现示例。
678

被折叠的 条评论
为什么被折叠?



