Test Instructions: There is a sequence of length n that satisfies the 1≤ai≤i, and the sign of each number is unknown. Please output a sign of the case, so that all the number of the and is 0. (n≤100000)
Solution:(I just want to continue to be a mouth-hu player quietly ...) ←_← but because this problem of greed is really too powerful! I just look, just stare at the puzzle for more than half an hour ... And the code is so short, I hit the code ... In fact, I don't quite understand why it must be sorted. )
The theoretical basis of the greedy part: the number of the former I can make up all the integers of 1~sum[i].
Proof: The second class of mathematical induction, n=1 when established, assuming n=k before all items are established when n=k+1. SUM[K+1]=SUM[K]+A[K+1].
Just prove that you can make up an integer between sum[k]+1~sum[k+1]. Set 1≤p≤a[k+1],sum[k]+p=sum[k]+a[k+1]-(a[k+1]-p).
Because 1≤a[i]≤i, easy to get sum[k]≥k,a[k+1]-p≤k. And because the known before the number of K can be 1~sum[k], so must be able to make up a[k+1]-p.
So just from the previous sum[k] inside cut out the number of a[k+1]-p to make up the sum[k]+p. So from 1~sum[k+1] All can be gathered out.
The implementation is the input when the sum, if it is an odd number of no solution, or else order, from large to small sweep over, select and for the SUM/2 of the symbol for the +, the rest is-.
1#include <cstdio>2#include <cstdlib>3#include <algorithm>4#include <iostream>5 using namespacestd;6 7 Const intn=100010;8 structnode{intX,id;} A[n];9 intB[n],ans[n];Ten One BOOLCMP (node X,node y) {returnX.x>y.x;} A intMain () - { - intN; the Long LongSum//cannot use int - while(~SCANF ("%d",&N)) - { -sum=0; + for(intI=1; i<=n;i++) - { +scanf"%d",&a[i].x); AA[i].id=i, sum+=a[i].x; at } - if(sum%2) {printf ("no\n");Continue;} -printf"yes\n"); -Sum/=2; -Sort (A +1, A +1+n,cmp); - for(intI=1; i<=n;i++) in { - if(a[i].x<=sum) ans[a[i].id]=1, sum-=a[i].x; to Elseans[a[i].id]=-1; + } -printf"%d", ans[1]); the for(intI=2; i<=n;i++) *printf"%d", Ans[i]); $printf"\ n");Panax Notoginseng } - return 0; the}
"UVA 1614" Hell on the (algorithmic efficiency-greed)