これ本番出てたらだいぶ手間取ってそう。
https://code.google.com/codejam/contest/11254486/dashboard#s=p2&a=2
問題
2wordからなるtopicがN個与えられる。
これらのtopicを任意の時系列で並べられるとき、過去のtopicの1つ目のwordと別のtopicの2つ目のwordから作れるtopicはfakeであると言える。
fakeである最大topic数を求めよ。
解法
1つ目のword群と2つ目のword群に対し、topicに対応する辺を張った二部グラフを考える。
幾つかのtopic=辺を選択した場合、未選択の辺の両端がどこか選択済み辺の両端であるなら、その未選択の辺はfake topicに相当する。
よって、選択済みの辺が最小辺カバーを成すなら、残りの辺がfake topicに相当し、その数が最大となる。
最小辺カバー数は|V|-|最大マッチング|なので、二部グラフの最大マッチングを求めればよい。
template<class V> class MaxFlow_Ford { public: struct edge { int to,reve;V cap;}; static const int MV = 3000; vector<edge> E[MV]; int vis[MV]; void add_edge(int x,int y,V cap,bool undir=false) { E[x].push_back((edge){y,(int)E[y].size(),cap}); E[y].push_back((edge){x,(int)E[x].size()-1,undir?cap:0}); } V dfs(int from,int to,V cf) { V tf; if(from==to) return cf; vis[from]=1; FORR(e,E[from]) if(vis[e.to]==0 && e.cap>0 && (tf = dfs(e.to,to,min(cf,e.cap)))>0) { e.cap -= tf; E[e.to][e.reve].cap += tf; return tf; } return 0; } V maxflow(int from, int to) { V fl=0,tf; while(1) { ZERO(vis); if((tf = dfs(from,to,numeric_limits<V>::max()))==0) return fl; fl+=tf; } } }; int N; string S[1010][2]; int T[1010][2]; map<string,int> M[2]; void solve(int _loop) { int f,i,j,k,l,x,y; cin>>N; M[0].clear(); M[1].clear(); FOR(i,N) cin>>S[i][0]>>S[i][1], M[0][S[i][0]]=M[1][S[i][1]]=0; x=y=0; MaxFlow_Ford<int> mf; FORR(r,M[0]) { r.second=x; mf.add_edge(0,x+1,1); x++; } FORR(r,M[1]) { r.second=y; mf.add_edge(1010+y,2020,1); y++; } FOR(i,N) mf.add_edge(1+M[0][S[i][0]],1010+M[1][S[i][1]],1); x = mf.maxflow(0,2020); _P("Case #%d: %d\n",_loop,N-(M[0].size()+M[1].size()-x)); }
まとめ
辺カバーのあたりの等式の理解があやふやなので、本番これ出たらちょっと怖かった。