先日のACLと少し関係あるか。
https://codeforces.com/contest/1307/problem/G
問題
N頂点の有向グラフが与えられる。各辺には通るのにかかる時間が設定されている。
以下のクエリに答えよ。
- 非負整数Xが与えられる。各辺を通る時間を合計Xまで増やせるとき、頂点1→Nへ移動する最短時間の最大値を求めよ。
解法
事前にX=0~100000のケースを求めておく。
元のグラフを、各辺容量が1・コストが時間とみなし最小コストフローを求める。
そうすると、あるコストcでいられる容量vが定まる。
この場合、合計で1だけ時間を増やせる場合、v本の辺のコストを1/vずつ増すことで全体で1/v時間が延びる。
int N,M; map<double,double> step; 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]; 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); 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) { dist[e.to]=d+e.cost; 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); flow -= lc; res += lc*dist[to]; step[dist[to]]+=lc; 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<51,double> mcf; double ret[101010]; int Q; void solve() { int i,j,k,l,r,x,y; string s; cin>>N>>M; FOR(i,M) { cin>>x>>y>>r; mcf.add_edge(x-1,y-1,1,r); } mcf.mincost(0,N-1,1e9); step[1e9]=1e9; double now=step.begin()->first; double cap=step.begin()->second; step.erase(step.begin()); FOR(i,101000) { ret[i]=now; double vol=1.0; while(now+vol/cap >= step.begin()->first) { vol -= (step.begin()->first-now)*cap; now = step.begin()->first; cap += step.begin()->second; step.erase(step.begin()); } now += vol/cap; } cin>>Q; while(Q--) { cin>>x; _P("%.12lf\n",ret[x]); } }
まとめ
ここらへん最小コストフローの動きを把握してないとさっとわからないな。