這道題實際上是挺簡單的。首先很容易發現最多人用的顏色的人數若是大於n/2,就確定不能讓所有人都成功戴上兩隻不一樣顏色的手套。反過來想,若是這我的數小於等於n/2又如何呢?的確,這就能讓所有人都能戴上兩隻不一樣顏色的手套(每一個人都留一隻本身本來的,再要別人的一隻手套就能夠了)。ios
1 #include <iostream> 2 #include <cmath> 3 #include <algorithm> 4 #include <bitset> 5 #include <cstring> 6 #include <list> 7 using namespace std; 8 struct Child{ 9 int color, num, mat; 10 }; 11 bool partition_cmp(const Child& c1, const Child& c2){ 12 return c1.color < c2.color; 13 } 14 bool sort_cmp(const Child& c1, const Child& c2){ 15 return c1.num < c2.num; 16 } 17 int main(){ 18 int n, m; 19 Child a[5000]; 20 int c[101]; 21 cin >> n >> m; 22 for (int i = 1; i <= m; i++){ 23 c[i] = 0; 24 } 25 for (int i = 0; i < n; i++){ 26 cin >> a[i].color; 27 a[i].num = i; 28 c[a[i].color]++; 29 } 30 int mx = 0; 31 for (int i = 1; i <= m; i++){ 32 if (c[mx] < c[i]){ 33 mx = i; 34 } 35 } 36 if (c[mx] * 2 > n){ 37 cout << 2 * (n - c[mx]) << endl; 38 int mcount = 0, miter = -1, d = n - c[mx]; 39 for (int i = 0; i < n; i++){ 40 if (a[i].color == mx){ 41 cout << a[i].color << " "; 42 if (d > 0){ 43 for (miter++; miter < n && a[miter].color == mx; miter++); 44 cout << a[miter].color << endl; 45 d--; 46 } 47 else{ 48 cout << a[i].color << endl; 49 } 50 } 51 else{ 52 cout << a[i].color << " " << mx << endl; 53 } 54 } 55 } 56 else{ 57 cout << n << endl; 58 sort(a, a + n, partition_cmp); 59 for (int i = 0; i < n; i++){ 60 a[i].mat = a[(i + c[mx]) % n].color; 61 } 62 sort(a, a + n, sort_cmp); 63 for (int i = 0; i < n; i++){ 64 cout << a[i].color << " " << a[i].mat << endl; 65 } 66 } 67 return 0; 68 }