USACO2.1.3--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 threedifferent 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
题解:贪心。方法非常的简单,先分别统计出1,2,3的各自个数,假设分别有,a,b,c个,然后从1扫描到a,遇到3就从n倒过来扫描,找到1就交换,遇见2就从a+1扫描到n,找到1和它交换。上述步骤执行完,这时1已经是有序的了。现在只要从a+b+1扫描到n,遇见2就从a+1开始扫描,找到3交换。结束之后序列就是有序的了。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /* 2 ID:spcjv51 3 PROG:sort3 4 LANG:C 5 */ 6 #include<stdio.h> 7 void swap(int *x,int *y) 8 { 9 int temp; 10 temp=*x; 11 *x=*y; 12 *y=temp; 13 } 14 int main(void) 15 { 16 freopen("sort3.in","r",stdin); 17 freopen("sort3.out","w",stdout); 18 int n,a,b,c,i,j,ans; 19 int f[1005]; 20 scanf("%d",&n); 21 memset(f,0,sizeof(f)); 22 a=0; 23 b=0; 24 c=0; 25 ans=0; 26 for(i=1; i<=n; i++) 27 { 28 scanf("%d",&f[i]); 29 if(f[i]==1)a++; 30 if(f[i]==2)b++; 31 if(f[i]==3)c++; 32 } 33 34 for(i=1; i<=a; i++) 35 { 36 while(f[i]==1)i++; 37 if(f[i]==3) 38 { 39 for(j=n;j>=0; j--) 40 if(f[j]==1) 41 { 42 swap(&f[i],&f[j]); 43 ans++; 44 break; 45 } 46 } 47 if(f[i]==2) 48 { 49 for(j=a+1; j<=n; j++) 50 if(f[j]==1) 51 { 52 swap(&f[i],&f[j]); 53 ans++; 54 break; 55 } 56 57 } 58 59 } 60 for(i=n-c+1; i<=n; i++) 61 { 62 while(f[i]==3)i++; 63 for(j=a+1; j<=n-c; j++) 64 if (f[j]==3) 65 { 66 swap(&f[i],&f[j]); 67 ans++; 68 break; 69 } 70 71 } 72 printf("%d\n",ans); 73 return 0; 74 }