1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
| #include<bits/stdc++.h>
using namespace std;
int s,t,s1,t1,k,cnt,n,m,head[1010],dis[1010],pid[1010],vis[1010];
struct no{ int from,to,nxt,c,w; }e[200010];
void add(int u,int v,int c,int w){ e[++cnt]={u,v,head[u],c,w}; head[u]=cnt; e[++cnt]={v,u,head[v],0,-w}; head[v]=cnt; }
int SPFA(){ memset(dis,0x3f,sizeof dis); memset(pid,0,sizeof pid); memset(vis,0,sizeof vis); queue<int>q; q.push(s); dis[s]=0; vis[s]=1; while(q.size()){ int u=q.front(); q.pop(); vis[u]=0; for(int i=head[u];i;i=e[i].nxt){ int v=e[i].to; if(e[i].c>0 and dis[v]>dis[u]+e[i].w){ dis[v]=dis[u]+e[i].w; pid[v]=i; if(!vis[v])q.push(v),vis[v]=1; } } } return dis[t]!=0x3f3f3f3f; }
pair<int,int>EK(){ int flow=0,cost=0; while(SPFA()){ int v=t,f=0x3f3f3f3f; while(pid[v]){f=min(f,e[pid[v]].c); v=e[pid[v]].from; } v=t; while(pid[v]){cost+=f*e[pid[v]].w; e[pid[v]].c-=f; e[pid[v]^1].c+=f; v=e[pid[v]].from;
} flow+=f; } return {cost,flow}; } int dif[2010],aa[2010],bb[2010],sum[2010];
int check(int v){ cnt=1; memset(head,0,sizeof head); memset(sum,0,sizeof sum); s1=n+1,t1=s1+1,s=t1+1,t=s+1; add(t1,s1,0x3f3f3f3f,0); for(int i=1;i<=m;i++)add(aa[i],bb[i],1,1);
for(int i=1;i<=n;i++){ if(dif[i]>v){ add(s1,i,2*v,0); sum[s1]-=dif[i]-v; sum[i]+=dif[i]-v; }else if(dif[i]>-v){ add(s1,i,dif[i]+v,0); add(i,t1,v-dif[i],0); }else{ add(i,t1,2*v,0); sum[i]-=-v-dif[i]; sum[t1]+=-v-dif[i]; } } int pd=0; for(int i=1;i<=t1;i++){ if(sum[i]>0)add(s,i,sum[i],0),pd+=sum[i]; if(sum[i]<0)add(i,t,-sum[i],0); } auto xx=EK(); if(xx.second==pd)return xx.first<=k; return 0; } int bh=0; map<string,int>mp; void solve(){ cin>>n>>m>>k; bh=0; memset(dif,0,sizeof dif); k=m-k; mp.clear(); for(int i=1;i<=m;i++){ string a,b; cin>>a>>b; if(!mp[a])mp[a]=++bh; if(!mp[b])mp[b]=++bh; aa[i]=mp[a]; bb[i]=mp[b]; dif[aa[i]]++; dif[bb[i]]--; } int l=0,r=n,ans; while(l<=r){ int mid=(l+r)>>1; if(check(mid))ans=mid,r=mid-1; else l=mid+1; } cout<<ans<<'\n'; } main(){ int tt,id=0; cin>>tt; while(tt--)id++,cout<<"Case #"<<id<<":\n",solve(); return 0; }
|