★4とあるけど、割とすんなり解けた。
https://yukicoder.me/problems/no/1678
問題
N個の国を順に移動する。
各国iの貨幣の価値はA[i]円である。
以下の条件で貨幣をやり取りできるとする。
- i国では、手持ちの円で任意枚数のその国の貨幣を買える
- i国では、指定されたいくつかの国の貨幣とi国の貨幣を交換可能である。ただし、1つの国あたり1枚のみ可能。
- 任意タイミングで手持ちの貨幣を売れる。その時の価格はA[i]である。
- 国の間の移動では、K枚を超える貨幣は持っていけない。
手持ちの円が十分にある条件のもと、円を最大いくら稼げるか。
解法
j国で買った貨幣をi国で交換し、即売るとA[i]-A[j]の利益を得られる。
そこで以下の最小コストフローを考えよう。
- 何もせず国を移動することを模して、頂点i→(i+1)にコスト0・容量無限の辺を張る。
- 上記利益を模して、頂点j→頂点iに利益(A[i]-A[j])・容量1の辺を張る
このグラフにフローKを流して得られる利益の最大値を求めよう。
このままだとコスト負の辺が出るので、適当にオフセットを加えて非負にする必要がある。
int N,K; ll dp[202020]; int A[202020],M[202020]; 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; } }; MinCostFlow<101010,ll> mcf; void solve() { int i,j,k,l,r,x,y; string s; cin>>N>>K; FOR(i,N-1) { mcf.add_edge(i,i+1,50,1<<30); } FOR(i,N) { cin>>A[i]>>M[i]; FOR(x,M[i]) { cin>>y; y--; mcf.add_edge(y,i,1,((ll)(i-y)<<30)-(A[i]-A[y])); } } ll ma=mcf.mincost(0,N-1,K); ll v=(ll)(N-1)*K<<30; cout<<v-ma<<endl; }
まとめ
ようやく最新問に追い付いた…。