hdu 3435 A new Graph Game

时间:2023-03-08 16:36:12

http://acm.hdu.edu.cn/showproblem.php?pid=3435

 #include <cstdio>
#include <iostream>
#include <cstring>
#include <queue>
#include <algorithm>
#define inf 0x3f3f3f3f
#define maxn 54444
using namespace std; queue<int>q;
struct node
{
int u,v,next,val,f;
} p[maxn];
int head[maxn];
bool vis[maxn];
int dis[maxn];
int pre[maxn];
int n,m,s,t,e; void add(int u,int v,int f,int c)
{
p[e].u=u;
p[e].v=v;
p[e].f=f;
p[e].val=c;
p[e].next=head[u];
head[u]=e++;
p[e].u=v;
p[e].v=u;
p[e].f=;
p[e].val=-c;
p[e].next=head[v];
head[v]=e++; } bool spfa()
{
int j,k,i;
while(!q.empty()) q.pop();
memset(vis,false,sizeof(vis));
memset(dis,0x3f,sizeof(dis));
memset(pre,-,sizeof(pre));
vis[s]=true;
dis[s]=;
q.push(s);
while(!q.empty())
{
int u=q.front();
q.pop();
vis[u]=false;
for(j=head[u]; j!=-; j=p[j].next)
{
int v=p[j].v;
if(p[j].f&&dis[u]+p[j].val<dis[v])
{
dis[v]=dis[u]+p[j].val;
pre[v]=j;
if(!vis[v])
{
vis[v]=true;
q.push(v);
}
}
}
}
return dis[t]!=inf;
} int mincost()
{
int ret=,u;
while(spfa())
{
u=pre[t];
ret+=dis[t];
while(u!=-)
{
p[u].f--;
p[u^].f++;
u=pre[p[u].u];
}
}
return ret;
}
int main()
{
int case1;
scanf("%d",&case1);
for(int k=; k<=case1; k++)
{
e=;
memset(head,-,sizeof(head));
scanf("%d%d",&n,&m);
s=;
t=*n+;
for(int i=; i<=m; i++)
{
int a,b,c;
scanf("%d%d%d",&a,&b,&c);
add(a,b+n,,c);
add(b,a+n,,c);
}
for(int i=; i<=n; i++)
{
add(s,i,,);
add(i+n,t,,);
}
int j;
int ans=mincost();
for(j=head[s]; j!=-; j=p[j].next)
if(p[j].f!=) break;
if(j==-) printf("Case %d: %d\n",k,ans);
else printf("Case %d: NO\n",k);
}
return ;
}