USACO Sorting a Three-Valued Sequence
首先來看一下題目:
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.
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組與第2組的交換,此時可以看到第0組和第2組的當前值發生了交換
同理,第3組與第6組交換
此時第1組、第4組、第8組的都不滿足兩兩交換的條件,因此第1組與第4組交換,此時第4組得到了滿足
最後將第1組與第8組交換
從上面的步驟可以看出來,如果出現了無法兩兩交換的元素,那麽每三組需要交換兩次。至於為什麽這樣做交換次數最少,我目前是靠的直覺。
/** ID: njuwz151 TASK: sort3 LANG: C++ **/ #include <bits/stdc++.h> using namespace std; const int maxn = 1005; int n; int number[maxn]; int expected[maxn]; int m_count[] = {0, 0, 0}; int swap_time = 0; void search(); int main() { freopen("sort3.in", "r", stdin); freopen("sort3.out", "w", stdout); cin >> n; for(int i = 0; i < n; i++) { cin >> number[i]; m_count[number[i]-1]++; } for(int i = 0; i < m_count[0]; i++) { expected[i] = 1; } for(int i = m_count[0]; i < m_count[0] + m_count[1]; i++) { expected[i] = 2; } for(int i = m_count[0] + m_count[1]; i < n; i++) { expected[i] = 3; } search(); cout << swap_time << endl; } void search() { for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { if(i == j) { continue; } if(expected[i] == number[j] && expected[j] == number[i] && number[i] != number[j]) { swap(number[i], number[j]); swap_time++; } } } int unpair = 0; for(int i = 0; i < n; i++) { if(expected[i]!=number[i]) { unpair++; } } swap_time += unpair / 3 * 2; } void swap(int& a, int& b) { int temp = a; a = b; b = temp; }
USACO Sorting a Three-Valued Sequence