Sorting a Three-Valued Sequence - USACO 2.1.2


sortingathree-valuedsequence - codetrick
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

给你一个只有1 2 3 的序列,要你排序,每次可以交换任意两个元素,问最小交换次数是多少
思路:贪心,先排1 ,如果1已经在位置上了,那就不要动了,如果是2那就和最前面的1交换,如果是3,那就和后面的1交换
http://www.cs.ru.ac.za/research/g04h2708/USACO-Greedy.html
The sequence has three parts: the part which will be 1 when in sorted order, 2 when in sorted order, and 3 when in sorted order. The greedy algorithm swaps as many as possible of the 1's in the 2 part with 2's in the 1 part, as many as possible 1's in the 3 part with 3's in the 1 part, and 2's in the 3 part with 3's in the 2 part. Once none of these types remains, the remaining elements out of place need to be rotated one way or the other in sets of 3. You can optimally sort these by swapping all the 1's into place and then all the 2's into place.

Analysis: Obviously, a swap can put at most two elements in place, so all the swaps of the first type are optimal. Also, it is clear that they use different types of elements, so there is no ``interference'' between those types. This means the order does not matter. Once those swaps have been performed, the best you can do is two swaps for every three elements not in the correct location, which is what the second part will achieve (for example, all the 1's are put in place but no others; then all that remains are 2's in the 3's place and vice-versa, and which can be swapped).
标程3:
http://lsharemy.com/wordpress/index.php/csit/usaco-prob-sorting-a-three-valued-sequence/
int main () {
    int s[1024];
    int n;
    int sc[4] = {0};
 
    ifstream fin("sort3.in");
    ofstream fout("sort3.out");
    fin>>n;
    for (int i = 0; i < n; i++) {
        fin>>s[i];
        sc[s[i]]++;
    }
    int s12 = 0, s13 = 0, s21 = 0, s31 = 0, s23 = 0, s32 = 0;
    for (int i = 0; i < sc[1]; i++){
        if (s[i] == 2) s12++;
        if (s[i] == 3) s13++;
    }
 
    for (int i = sc[1]; i < sc[1]+sc[2]; i++){
        if (s[i] == 1) s21++;
        if (s[i] == 3) s23++;
    }
 
    for (int i = sc[1]+sc[2]; i < sc[1]+sc[2]+sc[3]; i++){
        if (s[i] == 1) s31++;
        if (s[i] == 2) s32++;
    }
 
    fout<<min(s12, s21)+min(s13, s31)+min(s23, s32) +
                    2*(max(s12, s21) - min(s12, s21))<<endl;
    return 0;
}
http://blog.csdn.net/zztant/article/details/7823887
  1.     for(i=0;i<N;i++)  
  2.     {  
  3.         fscanf(fin,"%d",&A[i]);  
  4.         B[i]=A[i];  
  5.     }  
  6.     qsort(A,N,sizeof(int),comp);   //A已排序   
  7.       
  8.     for(i=0;i<N;i++)  
  9.     {  
  10.                 temp[A[i]][B[i]]++;  
  11.     }  
  12.     count=fabs(temp[1][2]-temp[2][1])*2+Min(temp[1][2],temp[2][1])+Min(temp[1][3],temp[3][1])+Min(temp[2][3],temp[3][2]);  

https://github.com/TomConerly/Competition-Programming/blob/master/USACO/Chapter2/sort3.java
* Solution: Count the number of 1s that are in a 2s spot, 1s in a 3s spot
* 2s in 1, 2s in 3, 3s in 1, 3s in 2. If there is a 1 in 2 and a 2 in a 1
* we want to switch them. So first do all of the moves which corrects 2.
* The number is min(1in2,2in1)+min(1in3,3in1)+min(2in3,3in2). Note that we
* have to have exactly k misplaced 1s, k misplaced 2s, and k misplaced 3s
* (try it out, this has to be true). So this is basically solving something like
* 312 but 3...31...12...2 which takes 2*k moves.


X. Simulation
http://www.boyu0.com/usaco-sorting-three-valued-sequence/
我们只要分别计算出1,2和3的个数,就能够知道最后排序的结果了,排序后第一个1出现的位置肯定是0,第一个2出现的位置为1的个数,第一个3出现的位置是1和2个数的和。。。
那么,我们要使交换的次数最少,我们只要保证当交换时,如果可以使两个交换的数字同时归位,那么就选择这个交换,如果不行,再做其他交换,那么交换的次数肯定就是最少的了。
我们只要通过程序用这个策略去模拟交换,最后统计交换的次数就行了
int main()
{
    FILE *fin  = fopen ("sort3.in", "r");
    FILE *fout = fopen ("sort3.out", "w");
    int n;
    int num[1000];
    int bucket[3] = {0};
    int i, j;
    int start, end;
    int ans = 0;
    
    fscanf(fin, "%d", &amp;n);
    for (i = 0; i &lt; n; ++i)
    {
        fscanf(fin, "%d", &amp;num[i]);
        ++bucket[num[i] - 1];
    }
    
    // bucket[i - 1] set to the start position of i when bucket is sorted.
    bucket[2] = bucket[1];
    bucket[1] = bucket[0];
    bucket[2] += bucket[0];
    bucket[0] = 0;
    // find 1 and change it is position
    for (i = 0; i < bucket[1]; ++i)
    {
        if (num[i] != 1)
        {
            start = bucket[num[i] - 1];
            end = num[i] == 2 ? bucket[2] : n;
            for (j = start; j &lt; end; ++j)
            {
                if (num[j] == 1)
                {
                    num[j] = num[i];
                    num[i] = 1;
                    ++ans;
                    break;
                }
            }
            
            if (j == end)
            {
                if (num[i] == 2)
                {
                    start = bucket[2];
                    end = n;
                }
                else
                {
                    start = bucket[1];
                    end = bucket[2];
                }
                for (j = start; j < end; ++j)
                {
                    if (num[j] == 1)
                    {
                        num[j] = num[i];
                        num[i] = 1;
                        ++ans;
                        break;
                    }
                }
            }
        }
    }
    
    // find 2
    for (i = bucket[1]; i < bucket[2]; ++i)
    {
        if (num[i] == 3)
            ++ans;
    }
    
    fprintf(fout, "%d\n", ans);
    
    return 0;
}
http://my.oschina.net/stormdpzh/blog/49082
    for(int i = 0; i < N; i++) {
        cin >> num[i];
        sorted[i] = num[i];
    }
     
    sort(sorted, sorted + N);
     
    memset(toChange, 0, sizeof(int));
     
    for(int i = 0; i < N; i++) {
        if(sorted[i] == 1 && num[i] == 2)
            toChange[1][2]++;
        else if(sorted[i] == 1 && num[i] == 3)
            toChange[1][3]++;
        else if(sorted[i] == 2 && num[i] == 1)
            toChange[2][1]++;
        else if(sorted[i] == 2 && num[i] == 3)
            toChange[2][3]++;
        else if(sorted[i] == 3 && num[i] == 1)
            toChange[3][1]++;
        else if(sorted[i] == 3 && num[i] == 2)
            toChange[3][2]++;
    }
     
    change = 0;
    int leave = 0;            //leave:两两交换之后剩下的
    for(int i = 1; i <= 2; i++) {
        for(int j = 1; j <= 3 - i; j++) {
            int minn = min(toChange[i][i+j], toChange[i+j][i]);
            change += minn;
            toChange[i][j+i] -= minn;
            toChange[j+i][i] -= minn;
            leave = leave + toChange[i][j+i] + toChange[j+i][i];
        }
    }
     
    change += leave * 2 / 3;
     
    cout << change << endl;
X. Simulation
http://qingtangpaomian.iteye.com/blog/1635261
http://bywbilly.blog.163.com/blog/static/2027010772012224103921168/
  1.     public static void main(String[] args) {  
  2.         try {  
  3. //          Scanner in = new Scanner(System.in);  
  4. //          PrintWriter pw = new PrintWriter(System.out);  
  5.               
  6.             Scanner in = new Scanner(new BufferedReader(new FileReader(  
  7.             "sort3.in")));  
  8.             PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(  
  9.             "sort3.out")));  
  10.               
  11.             int num = in.nextInt();  
  12.             int cnt = 0;  
  13.             int[] input = new int[num];  
  14.             int[] sorted = new int[num];  
  15.             int[] position = new int[4];  
  16.               
  17.             for (int i=0;i<num;i++){  
  18.                 int temp = in.nextInt();  
  19.                 if (temp == 1){  
  20.                     position[1]++;  
  21.                 } else if (temp == 2){  
  22.                     position[2]++;  
  23.                 } else {  
  24.                     position[3]++;  
  25.                 }  
  26.                 input[i] = temp;  
  27.                 sorted[i] = temp;  
  28.             }  
  29.               
  30.             Arrays.sort(sorted);  
  31.             position[3] = position[2] + position[1];  
  32.             position[2] = position[1];  
  33.             position[1] = 0;  
  34.               
  35.             for (int i=position[1];i<position[2];i++){  
  36.                 int temp = input[i];  
  37.                 if (temp == 2){  
  38.                     for (int j=position[2];j<num;j++){  
  39.                         if (input[j] == sorted[i]){  
  40.                             exchange(i, j, input);  
  41.                             cnt ++;  
  42.                             break;  
  43.                         }  
  44.                     }  
  45.                 } else if (temp == 3){  
  46.                     for (int j=num-1;j>=position[2];j--){  
  47.                         if (input[j] == sorted[i]){  
  48.                             exchange(i, j, input);  
  49.                             cnt ++;  
  50.                             break;  
  51.                         }  
  52.                     }  
  53.                 }  
  54.             }  
  55.               
  56.             for (int i=position[2];i<position[3];i++){  
  57.                 int temp = input[i];  
  58.                 if (temp == 3){  
  59.                     for (int j=num-1;j>=position[2];j--){  
  60.                         if (input[j] == sorted[i]){  
  61.                             exchange(i, j, input);  
  62.                             cnt ++;  
  63.                             break;  
  64.                         }  
  65.                     }  
  66.                 }  
  67.             }  
  68.               
  69.             pw.println(cnt);  
  70.             pw.close();  
  71.             in.close();  
  72.         } catch (Exception e) {  
  73.             e.printStackTrace();  
  74.         }  
  75.           
  76.     }  
  77.       
  78.     public static void exchange(int i,int j,int[] target){  
  79.         int temp = target[i];  
  80.         target[i] = target[j];  
  81.         target[j] = temp;  
  82.     } 
http://blog.sina.com.cn/s/blog_5256c1ba0100x8ms.html
Read full article from sortingathree-valuedsequence - codetrick

Labels

LeetCode (1432) GeeksforGeeks (1122) LeetCode - Review (1067) Review (882) Algorithm (668) to-do (609) Classic Algorithm (270) Google Interview (237) Classic Interview (222) Dynamic Programming (220) DP (186) Bit Algorithms (145) POJ (141) Math (137) Tree (132) LeetCode - Phone (129) EPI (122) Cracking Coding Interview (119) DFS (115) Difficult Algorithm (115) Lintcode (115) Different Solutions (110) Smart Algorithm (104) Binary Search (96) BFS (91) HackerRank (90) Binary Tree (86) Hard (79) Two Pointers (78) Stack (76) Company-Facebook (75) BST (72) Graph Algorithm (72) Time Complexity (69) Greedy Algorithm (68) Interval (63) Company - Google (62) Geometry Algorithm (61) Interview Corner (61) LeetCode - Extended (61) Union-Find (60) Trie (58) Advanced Data Structure (56) List (56) Priority Queue (53) Codility (52) ComProGuide (50) LeetCode Hard (50) Matrix (50) Bisection (48) Segment Tree (48) Sliding Window (48) USACO (46) Space Optimization (45) Company-Airbnb (41) Greedy (41) Mathematical Algorithm (41) Tree - Post-Order (41) ACM-ICPC (40) Algorithm Interview (40) Data Structure Design (40) Graph (40) Backtracking (39) Data Structure (39) Jobdu (39) Random (39) Codeforces (38) Knapsack (38) LeetCode - DP (38) Recursive Algorithm (38) String Algorithm (38) TopCoder (38) Sort (37) Introduction to Algorithms (36) Pre-Sort (36) Beauty of Programming (35) Must Known (34) Binary Search Tree (33) Follow Up (33) prismoskills (33) Palindrome (32) Permutation (31) Array (30) Google Code Jam (30) HDU (30) Array O(N) (29) Logic Thinking (29) Monotonic Stack (29) Puzzles (29) Code - Detail (27) Company-Zenefits (27) Microsoft 100 - July (27) Queue (27) Binary Indexed Trees (26) TreeMap (26) to-do-must (26) 1point3acres (25) GeeksQuiz (25) Merge Sort (25) Reverse Thinking (25) hihocoder (25) Company - LinkedIn (24) Hash (24) High Frequency (24) Summary (24) Divide and Conquer (23) Proof (23) Game Theory (22) Topological Sort (22) Lintcode - Review (21) Tree - Modification (21) Algorithm Game (20) CareerCup (20) Company - Twitter (20) DFS + Review (20) DP - Relation (20) Brain Teaser (19) DP - Tree (19) Left and Right Array (19) O(N) (19) Sweep Line (19) UVA (19) DP - Bit Masking (18) LeetCode - Thinking (18) KMP (17) LeetCode - TODO (17) Probabilities (17) Simulation (17) String Search (17) Codercareer (16) Company-Uber (16) Iterator (16) Number (16) O(1) Space (16) Shortest Path (16) itint5 (16) DFS+Cache (15) Dijkstra (15) Euclidean GCD (15) Heap (15) LeetCode - Hard (15) Majority (15) Number Theory (15) Rolling Hash (15) Tree Traversal (15) Brute Force (14) Bucket Sort (14) DP - Knapsack (14) DP - Probability (14) Difficult (14) Fast Power Algorithm (14) Pattern (14) Prefix Sum (14) TreeSet (14) Algorithm Videos (13) Amazon Interview (13) Basic Algorithm (13) Codechef (13) Combination (13) Computational Geometry (13) DP - Digit (13) LCA (13) LeetCode - DFS (13) Linked List (13) Long Increasing Sequence(LIS) (13) Math-Divisible (13) Reservoir Sampling (13) mitbbs (13) Algorithm - How To (12) Company - Microsoft (12) DP - Interval (12) DP - Multiple Relation (12) DP - Relation Optimization (12) LeetCode - Classic (12) Level Order Traversal (12) Prime (12) Pruning (12) Reconstruct Tree (12) Thinking (12) X Sum (12) AOJ (11) Bit Mask (11) Company-Snapchat (11) DP - Space Optimization (11) Dequeue (11) Graph DFS (11) MinMax (11) Miscs (11) Princeton (11) Quick Sort (11) Stack - Tree (11) 尺取法 (11) 挑战程序设计竞赛 (11) Coin Change (10) DFS+Backtracking (10) Facebook Hacker Cup (10) Fast Slow Pointers (10) HackerRank Easy (10) Interval Tree (10) Limited Range (10) Matrix - Traverse (10) Monotone Queue (10) SPOJ (10) Starting Point (10) States (10) Stock (10) Theory (10) Tutorialhorizon (10) Kadane - Extended (9) Mathblog (9) Max-Min Flow (9) Maze (9) Median (9) O(32N) (9) Quick Select (9) Stack Overflow (9) System Design (9) Tree - Conversion (9) Use XOR (9) Book Notes (8) Company-Amazon (8) DFS+BFS (8) DP - States (8) Expression (8) Longest Common Subsequence(LCS) (8) One Pass (8) Quadtrees (8) Traversal Once (8) Trie - Suffix (8) 穷竭搜索 (8) Algorithm Problem List (7) All Sub (7) Catalan Number (7) Cycle (7) DP - Cases (7) Facebook Interview (7) Fibonacci Numbers (7) Flood fill (7) Game Nim (7) Graph BFS (7) HackerRank Difficult (7) Hackerearth (7) Inversion (7) Kadane’s Algorithm (7) Manacher (7) Morris Traversal (7) Multiple Data Structures (7) Normalized Key (7) O(XN) (7) Radix Sort (7) Recursion (7) Sampling (7) Suffix Array (7) Tech-Queries (7) Tree - Serialization (7) Tree DP (7) Trie - Bit (7) 蓝桥杯 (7) Algorithm - Brain Teaser (6) BFS - Priority Queue (6) BFS - Unusual (6) Classic Data Structure Impl (6) DP - 2D (6) DP - Monotone Queue (6) DP - Unusual (6) DP-Space Optimization (6) Dutch Flag (6) How To (6) Interviewstreet (6) Knapsack - MultiplePack (6) Local MinMax (6) MST (6) Minimum Spanning Tree (6) Number - Reach (6) Parentheses (6) Pre-Sum (6) Probability (6) Programming Pearls (6) Rabin-Karp (6) Reverse (6) Scan from right (6) Schedule (6) Stream (6) Subset Sum (6) TSP (6) Xpost (6) n00tc0d3r (6) reddit (6) AI (5) Abbreviation (5) Anagram (5) Art Of Programming-July (5) Assumption (5) Bellman Ford (5) Big Data (5) Code - Solid (5) Code Kata (5) Codility-lessons (5) Coding (5) Company - WMware (5) Convex Hull (5) Crazyforcode (5) DFS - Multiple (5) DFS+DP (5) DP - Multi-Dimension (5) DP-Multiple Relation (5) Eulerian Cycle (5) Graph - Unusual (5) Graph Cycle (5) Hash Strategy (5) Immutability (5) Java (5) LogN (5) Manhattan Distance (5) Matrix Chain Multiplication (5) N Queens (5) Pre-Sort: Index (5) Quick Partition (5) Quora (5) Randomized Algorithms (5) Resources (5) Robot (5) SPFA(Shortest Path Faster Algorithm) (5) Shuffle (5) Sieve of Eratosthenes (5) Strongly Connected Components (5) Subarray Sum (5) Sudoku (5) Suffix Tree (5) Swap (5) Threaded (5) Tree - Creation (5) Warshall Floyd (5) Word Search (5) jiuzhang (5)

Popular Posts