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.
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} |
9 2 2 1 3 3 3 2 3 1
A single line containing the number of exchanges required
4
/* ID: guangxue1 PROG: sort3 LANG: C++ */ #include <fstream> #include <stdlib.h> #include <math.h> #include <algorithm> using namespace std; int queue[1000]; int queue2[1000]; int a,b; int ab,ac,ba,bc,ca,cb; int cnt; int main() { ifstream fin("sort3.in"); ofstream fout("sort3.out"); int n; fin>>n; for(int i=0; i<n; ++i) { fin>>queue[i]; //queue2[i]=queue[i]; switch(queue[i]) { case 1: ++a; break; case 2: ++b; } } // qsort(queue2,n,sizeof(queue[0]),cmp); for(int i=0; i<a; ++i) switch(queue[i]) { case 2: ++ab; break; case 3: ++ac; } for(int i=a; i<a+b; ++i) switch(queue[i]) { case 1: ++ba; break; case 3: ++bc; } for(int i=a+b; i<n; ++i) switch(queue[i]) { case 1: ++ca; break; case 2: ++cb; } cnt+=min(ab,ba)+min(ac,ca)+min(bc,cb); cnt+=abs(ab-ba)+abs(ac-ca); fout<<cnt<<endl; return 0; }
这回我用了用库函数,知道了include stdlib.h本来想事用qsort,后来一想没必要。
algorrithm是为了min和max用的,math.h是abs用的(浮点的要用fabs);
stdlib要加h,math也一样,不明白为什么。。。。。。