usaco2.1.3(sort3)
题目:
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
题意很简单,就是给个乱序,问排好后最少需要多少次交换
代码:
/* ID:614433244 PROG: sort3 LANG: C++ */ #include"iostream" #include"cstdio" #include"algorithm" using namespace std; int t[1005]; int main() { freopen( "sort3.in","r",stdin ); freopen( "sort3.out","w",stdout ); int n; int a,b,c; scanf("%d",&n); int i,j; a=b=c=0; for( i=1;i<=n;i++ ) { scanf("%d",&t[i]); if( t[i]==1 ) a++; if( t[i]==2 ) b++; if( t[i]==3 ) c++; } int ans=0; for( i=1;i<=a;i++ ) { if( t[i]==2 ) { for( j=a+1;j<=n;j++ )//在这个地方写j=a+1时不小心写成了j==a+1,wa了好久,后来一步一步打印才看出来没有进入循环体,悲剧 { if( t[j]==1 ) { t[i]=1; t[j]=2; ans++; break; } } } if( t[i]==3 ) { for( j=n;j>a;j-- ) { if( t[j]==1 ) { t[i]=1; t[j]=3; ans++; break; } } } } for( i=a+1;i<=a+b;i++ ) { if( t[i]==3 ) ans++; } printf("%d\n",ans); return 0; }
浙公网安备 33010602011771号