Usaco sorting a three-valued Sequence

Source: Internet
Author: User

The main idea: to give you a 1 2 3 sequence, you can sort, to exchange any two elements at a time, ask the minimum number of exchanges

Idea: Greedy, first row 1, if 1 is already in position, then do not move, if it is 2 that and the front of the 1 exchange, if 3, then and the back of the 1 exchange

1 /*{2 id:a42984423 Prob:sort34 lang:c++5 }6 */7#include <iostream>8#include <fstream>9 #defineMAXN 5000Ten using namespacestd; OneIfstream Fin ("sort3.in"); AOfstream Fout ("Sort3.out"); - //#define FIN CIN - //#define Fout cout the intA[MAXN],LISTONE[MAXN]; - intMain () - { -     intN,one=0, two=0, three=0, h=0, r=0, l=0, ans=0; +Fin>>N; -      for(intI=1; i<=n;i++) +     { AFin>>A[i]; at         if(a[i]==1) one++,listone[++r]=i; -         if(a[i]==2) two++; -         if(a[i]==3) three++; -     } -      for(intI=1; i<=one;i++)if(a[i]==1) l++; -      for(intI=1; i<=one;i++) in     { -         if(a[i]==1)Continue; to         Else if(a[i]==2) +         { -Swap (a[i],a[listone[++L]]); theans++; *         } $         Else if(a[i]==3)Panax Notoginseng         { -Swap (a[i],a[listone[r--]]); theans++; +         } A     } the      for(intI=one+1; i<=one+two;i++) +     { -         if(a[i]==3) ans++; $     } $fout<<ans<<Endl; -     return 0; -}

Usaco sorting a three-valued Sequence

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.