Although this problem can be n^3 by violence, but there is a kind of n^2 method, enumeration B, for B, enumerate A and C respectively, get the best solution for this B, and then select an optimal from B.
To ensure that the dictionary order is minimal, as long as small to large enumeration is good
There is a DP practice, I do not understand ...
Thanks to Moonflyer, the sauce God gave me this idea
#include <cstdio>#include<algorithm>#include<cmath>#include<cstring>using namespacestd;Const intMAXN = the+5;intCNT[MAXN];intSUM[MAXN];intMain () {//freopen ("In.txt", "R", stdin); intT; scanf ("%d",&T); intCas =0; while(t--){ intN; memset (CNT,0,sizeof(CNT)); scanf ("%d",&N); for(inti =0; I < n; i++){ intT; scanf ("%d",&t); Cnt[t]++; } memcpy (sum,cnt,sizeof(CNT)); for(inti =1; I <= the; i++) Sum[i]+ = sum[i-1]; DoubleAve = n/4.0; DoubleBDIF =1e30; intBesta =0, Bestb =1, BESTC =2; for(intb =1; b < the; b++){ DoubleDIF1 = Fabs (sum[0]-ave) + fabs (sum[b]-sum[0]-Ave); intPBA =0; for(intA =1; a < b; a++){ DoubleNDIF = Fabs (sum[a]-ave) +fabs (sum[b]-sum[a]-Ave); if(ndif<dif1) {DIF1= NDIF; PBA =A; } } intPBC = B +1; DoubleDif2 = Fabs (sum[b+1]-SUM[B]) + fabs (sum[ the]-sum[b+1]); for(intc = B +2; c<= the; C++){ DoubleNDIF = Fabs (sum[c]-sum[b]-ave) +fabs (sum[ the]-sum[c]-Ave); if(Ndif <dif2) {Dif2= NDIF; PBC =C; } } if(dif1+dif2<bdif) {Besta= PBA; Bestb = b; BESTC =PBC; Bdif= dif1+Dif2; }} printf ("Case %d:%d%d%d\n",++CAS,BESTA,BESTB,BESTC); } return 0;}
UVA12904 Load balancing Midway Encounter method