USACO Section 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 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
题意:给定一个序列,里面只含0 1 2这三个数字,任意交换两个数,使得最终有序,最少需要交换多少次。
分析:分成三个部分,第一部分最终只有1,第二部分最终是2,第三部分最终是3,第一部分的2与第二部分的1交换代价为1,第一部分的3与第三部分的1交换代价为1,第二部分的3也第三部分的2交换代价为1,把上面的交换完成或要么没有了,要么就是需要两两交换代价为2。
View Code
1 /* 2 ID: dizzy_l1 3 LANG: C++ 4 TASK: sort3 5 */ 6 #include<iostream> 7 #include<cstring> 8 #include<cstdio> 9 #define MAXN 1001 10 11 using namespace std; 12 13 int s[MAXN]; 14 int cnt[4][4]; 15 16 int main() 17 { 18 //freopen("sort3.in","r",stdin); 19 //freopen("sort3.out","w",stdout); 20 int n,a,b,c,i; 21 while(scanf("%d",&n)==1) 22 { 23 a=b=c=0; 24 for(i=1;i<=n;i++) 25 { 26 scanf("%d",&s[i]); 27 if(s[i]==1) a++; 28 else if(s[i]==2) b++; 29 else c++; 30 } 31 memset(cnt,0,sizeof(cnt)); 32 for(i=1;i<=a;i++) 33 { 34 cnt[1][s[i]]++; 35 } 36 for(;i<=a+b;i++) 37 { 38 cnt[2][s[i]]++; 39 } 40 for(;i<=a+b+c;i++) 41 { 42 cnt[3][s[i]]++; 43 } 44 int ans=0; 45 ans=min(cnt[1][2],cnt[2][1]); 46 cnt[1][2]-=min(cnt[1][2],cnt[2][1]); 47 cnt[2][1]-=min(cnt[1][2],cnt[2][1]); 48 ans+=min(cnt[1][3],cnt[3][1]); 49 cnt[1][3]-=min(cnt[1][3],cnt[3][1]); 50 cnt[3][1]-=min(cnt[1][3],cnt[3][1]); 51 ans+=min(cnt[2][3],cnt[3][2]); 52 cnt[2][3]-=min(cnt[2][3],cnt[3][2]); 53 cnt[3][2]-=min(cnt[2][3],cnt[3][2]); 54 ans+=max(cnt[1][2],cnt[1][3])*2; 55 printf("%d\n",ans); 56 } 57 return 0; 58 }


浙公网安备 33010602011771号