USACO 2.1 Sorting a Three-Valued Sequence

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

题目大意:三值排序,就是说一个有N个数字的序列(数字的范围是1到3),现在想排成升序,问最少几次交换。
思路:大概的想法,最优的可以交换的数字有两种,第一种是交换后两个都到了自己该在的位置比如(2,1,3),第二种是需要交换“一轮”,比如(3,2,1),第一种的代价是一,第二种的代价是2,总的思路就是先确定三个值排序结束后各个数字该在的范围,然后找出各个位置不对的数字的个数(比如a2代表在1排完序该在的位置上有a2个2,a3代表有几个3,b代表2排完序的位置或者说长度),先把可以两两交换的交换完,然后剩下的都是循环交换的,加起来除以三乘2就好,代码如下,略丑
 1 /*
 2 ID:fffgrdc1
 3 PROB:sort3
 4 LANG:C++
 5 */
 6 #include<cstdio>
 7 #include<iostream>
 8 using namespace std;
 9 int a[1005];
10 int main()
11 {
12     freopen("sort3.in","r",stdin);
13     freopen("sort3.out","w",stdout);
14     int n,ans=0;
15     scanf("%d",&n);
16     int a2=0,a3=0,b1=0,b3=0,c1=0,c2=0,al=0,bl=0,cl=0;
17     for(int i=1;i<=n;i++)
18     {
19         scanf("%d",&a[i]);
20         if(a[i]==1)al++;
21         else if(a[i]==2)bl++;
22         else cl++;
23     }
24     for(int i=1;i<=al;i++)
25     {
26         if(a[i]==2)
27         {
28             a2++;
29         }
30         else if(a[i]==3)a3++;
31     }
32     for(int i=al+1;i<=al+bl;i++)
33     {
34         if(a[i]==1)b1++;
35         else if(a[i]==3)b3++;
36     }
37     for(int i=al+bl+1;i<=al+bl+cl;i++)
38     {
39         if(a[i]==1)c1++;
40         else if(a[i]==2)c2++;
41     }
42     //printf("%d %d %d  %d %d %d  %d %d %d
",al,a2,a3,bl,b1,b3,cl,c1,c2);
43     int temp=min(c2,b3);
44     ans+=temp;c2-=temp;b3-=temp;
45     temp=min(c1,a3);
46     ans+=temp;c1-=temp;a3-=temp;
47     temp=min(a2,b1);
48     ans+=temp;a2-=temp;b1-=temp;
49     temp=a2+a3+b1+b3+c1+c2;
50     temp/=3;
51     temp*=2;
52     ans+=temp;
53     //printf("%d %d %d  %d %d %d  %d %d %d
",al,a2,a3,bl,b1,b3,cl,c1,c2);
54     printf("%d
",ans);
55     return 0;
56 
57 }

看了其他人的题解,和我的思路大同小异。这题没什么意思。。。

原文地址:https://www.cnblogs.com/xuwangzihao/p/5005775.html