标签:条件 UI sea 情况 silver ges ati std eve
首先来看一下题目:
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
这道题的思路是这样的,首先,如果可以两两交换的,就两两交换,否则就三个轮换。
在没有任何改变的情况下,值是这样的:
此时所说的两两交换首先是第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
标签:条件 UI sea 情况 silver ges ati std eve
原文地址:http://www.cnblogs.com/NJUWZ/p/7056309.html