http://acm.hdu.edu.cn/showproblem.php?pid=2426
#include <iostream>
#include <cstdio>
using namespace std;
const int oo=1e7;
const int mm=111111;
const int mn=8888;
int node,src,dest,edge,ans;
int ver[mm],flow[mm],cost[mm],next[mm];
int head[mn],dis[mn],p[mn],q[mn],vis[mn],work[mn];
void prepare(int _node,int _src,int _dest)
{
node=_node,src=_src,dest=_dest;
for(int i=0;i<node;++i)head[i]=-1,vis[i]=0;
edge=0;
}
void addedge(int u,int v,int f,int c)
{
ver[edge]=v,flow[edge]=f,cost[edge]=c,next[edge]=head[u],head[u]=edge++;
ver[edge]=u,flow[edge]=0,cost[edge]=-c,next[edge]=head[v],head[v]=edge++;
}
bool spfa()
{
int i,u,v,l,r=0,tmp;
for(i=0;i<node;i++) dis[i]=-oo;
dis[q[r++]=src]=0;
p[src]=p[dest]=-1;
for(l=0;l!=r;(++l>=mn)?l=0:l)
for(i=head[u=q[l]],vis[u]=0;i>=0;i=next[i])
if(flow[i]&&dis[v=ver[i]]<(tmp=dis[u]+cost[i]))
{
dis[v]=tmp;//cout<<"u="<<u<<" v="<<v<<" tmp="<<tmp<<endl;
p[v]=i^1;
if(vis[v]) continue;
vis[q[r++]=v]=1;
if(r>=mn) r=0;
}
return p[dest]>-1;
}
int Spfaflow()
{
int i,ret=0,delta;
while(spfa())
{
for(i=p[dest],delta=oo;i>=0;i=p[ver[i]])
if(flow[i^1]<delta) delta=flow[i^1];
ans+=delta;
for(i=p[dest];i>=0;i=p[ver[i]])
flow[i]+=delta,flow[i^1]-=delta;
ret+=delta*dis[dest];//cout<<"ret="<<ret<<endl;
}
return ret;
}
int main()
{
int n,m,k,s,r,v,i,cas=0;
while(~scanf("%d%d%d",&n,&m,&k))
{
prepare(n+m+2,0,n+m+1);
if(n>m)
{
printf("Case %d: -1\n",++cas);
continue;
}
for(i=1;i<=n;i++)
addedge(src,i,1,0);
for(i=1;i<=m;i++)
addedge(n+i,dest,1,0);
while(k--)
{
scanf("%d%d%d",&s,&r,&v);
s++;
r++;
if(v>=0)
addedge(s,n+r,oo,v);
}
ans=0;
int kk=Spfaflow();
if(ans==n)
printf("Case %d: %d\n",++cas,kk);
else
printf("Case %d: -1\n",++cas);
}
return 0;
}