年末最後のSRMは、PC環境の整備が間に合わず不参加でした…。
https://community.topcoder.com/stat?c=problem_statement&pm=17349
問題
3つのN要素の整数列A,B,Cが与えられる。
各数列から、NA,NB,NC要素を選び、その総和を最大化したい。
ただし、複数の数列から同じindexの要素を選ぶことはできない。
総和の最大値を求めよ。
解法
自分は無駄に最小コストフローで、損失の最小化を図ってしまった。
別解法としては、i番目のindexについて、これまで何要素をA,B,Cのどこから選んだかを状態として、A,B,Cのどこから追加で選ぶかを求める単純なO(N*NA*NB*NC)のDPでも解けるようだ。
template<int NV,class V> class MinCostFlow { public: struct edge { int to; V capacity; V cost; int reve;}; vector<edge> E[NV]; int prev_v[NV], prev_e[NV]; V dist[NV]; V pot[NV]; void add_edge(int x,int y, V cap, V cost) { E[x].push_back((edge){y,cap,cost,(int)E[y].size()}); E[y].push_back((edge){x,0, -cost,(int)E[x].size()-1}); /* rev edge */ } V mincost(int from, int to, ll flow) { V res=0; int i,v; ZERO(prev_v); ZERO(prev_e); fill(pot, pot+NV, 0); while(flow>0) { fill(dist, dist+NV, numeric_limits<V>::max()/2); dist[from]=0; priority_queue<pair<V,int> > Q; Q.push(make_pair(0,from)); while(Q.size()) { V d=-Q.top().first; int cur=Q.top().second; Q.pop(); if(dist[cur]!=d) continue; if(d==numeric_limits<V>::max()/2) break; FOR(i,E[cur].size()) { edge &e=E[cur][i]; if(e.capacity>0 && dist[e.to]>d+e.cost+pot[cur]-pot[e.to]) { dist[e.to]=d+e.cost+pot[cur]-pot[e.to]; prev_v[e.to]=cur; prev_e[e.to]=i; Q.push(make_pair(-dist[e.to],e.to)); } } } if(dist[to]==numeric_limits<V>::max()/2) return -1; V lc=flow; for(v=to;v!=from;v=prev_v[v]) lc = min(lc, E[prev_v[v]][prev_e[v]].capacity); FOR(i,NV) pot[i]+=dist[i]; flow -= lc; res += lc*pot[to]; for(v=to;v!=from;v=prev_v[v]) { edge &e=E[prev_v[v]][prev_e[v]]; e.capacity -= lc; E[v][e.reve].capacity += lc; } } return res; } }; class SelectFromArrays { public: int maxSum(vector <int> A, vector <int> B, vector <int> C, int NA, int NB, int NC) { int i,N=A.size(); MinCostFlow<2020,ll> mcf; mcf.add_edge(0,1,NA,0); mcf.add_edge(0,2,NB,0); mcf.add_edge(0,3,NC,0); FOR(i,N) { mcf.add_edge(1,100+i,1,1000000-A[i]); mcf.add_edge(2,100+i,1,1000000-B[i]); mcf.add_edge(3,100+i,1,1000000-C[i]); mcf.add_edge(100+i,4,1,0); } return (NA+NB+NC)*1000000-mcf.mincost(0,4,NA+NB+NC); } }
まとめ
最小コストフローのライブラリを除けば、どちらでも実装量大差ないっちゃないけどね。