Poj2454 Jersey politics-Greedy + randomization algorithm

Source: Internet
Author: User

When I first read this question, it is clear that everyone has come up with greedy + SEARCH + pruning, but the poj evaluation machine is not powerful, so it must be TLE. So, of course, we know the power of random.

First, verify the correctness of the greedy algorithm:

Policy: sort the N * 3 elements in descending order, and divide the N * 2 elements into two groups. The last n elements are grouped into one group.

Proof: if you do not select this option, the total number of the first two groups will be smaller than the total number of selected groups, which is more likely to fail. Pass.

Randomization algorithm:

Each time an element is selected from the first two sets for exchange, if the conditions are met, the output is directly halt.

I won't prove this randomization.

Code

Program POJ2454;//By_PoetshyConstmaxn=200;Vari,j,k,m,n:Longint;a,rank:Array[1..maxn]of Longint;v:Array[1..maxn]of Boolean;all,sum,temp:Longint;Procedure Qsort(l,r:Longint);var i,j,k,temp:Longint;begini:=l;j:=r;k:=a[(i+j)>>1];repeatwhile a[i]>k do inc(i);while a[j]<k do dec(j);if i<=j thenbegintemp:=a[i];a[i]:=a[j];a[j]:=temp;temp:=rank[i];rank[i]:=rank[j];rank[j]:=temp;inc(i);dec(j);end;until i>j;if i<r then Qsort(i,r);if l<j then Qsort(l,j);end;Procedure Print;var j:Longint;beginfor j:=1 to n do writeln(rank[j]);for j:=n+1 to n*2 do writeln(rank[j]);for j:=n*2+1 to n*3 do writeln(rank[j]);end;Function check:Boolean;beginif sum<=500*n then exit(false);if all-sum<=500*n then exit(false);exit(true);end;BEGINreadln(n);for i:=1 to n*3 dobeginreadln(a[i]);rank[i]:=i;end;Qsort(1,n*3);sum:=0;m:=1;fillchar(v,sizeof(v),0);for i:=1 to n<<1 do inc(all,a[i]);for i:=1 to n do begininc(sum,a[i]);v[i]:=true;end;randomize;while true do beginif Check then beginPrint;halt;end;i:=random(n)+1;j:=random(n)+n+1;inc(sum,a[j]);dec(sum,a[i]);temp:=a[i];a[i]:=a[j];a[j]:=temp;temp:=rank[i];rank[i]:=rank[j];rank[j]:=temp;end;END.

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.