HDU-3435 A new Graph Game

继续是最小权值环覆盖。

注意的是边为双向。

#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <fstream>
#include <iostream>
#include <vector>
#include <cctype>
#define rep(i, l, r) for(int i=l; i<=r; i++)
#define clr(x, c) memset(x, c, sizeof(x))
#define N 1234
#define M 23456
#define MAX 1<<30
#define ll long long
using namespace std;
int read()
{
	int x=0, f=1; char ch=getchar();
	while (!isdigit(ch)) { if (ch=='-') f=-1; ch=getchar(); }
	while (isdigit(ch)) { x=x*10+ch-'0'; ch=getchar(); }
	return x*f;
}

struct edge{int x, y, z, n;} e[M]; int fir[N], en;
int n, m, l[N], st[N], lx[N], ly[N];
bool vx[N], vy[N];

inline void Add(int x, int y, int z)
{
	en++, e[en]=(edge){x, y, z, fir[x]}, fir[x]=en;
	en++, e[en]=(edge){y, x, z, fir[y]}, fir[y]=en;
}

bool Find(int x)
{
	vx[x]=1;
	for(int o=fir[x], y=e[o].y; o; o=e[o].n, y=e[o].y)
	{
		if (vy[y]) continue;
		int a=lx[x]+ly[y]-e[o].z;
		if (!a)
		{
			vy[y]=1; if (!l[y] || Find(l[y])) { l[y]=x; return 1; }
		}
		else st[y]=min(st[y], a);
	}
	return false;
}

inline int km()
{
	clr(ly, 0); clr(l, 0); rep(i, 1, n) lx[i]=-MAX;
	rep(i, 1, en) if (lx[e[i].x]<e[i].z) lx[e[i].x]=e[i].z;
	rep(i, 1, n) if (lx[i]==-MAX) return 1;
	rep(i, 1, n) 
	{
		rep(j, 1, n) st[j]=MAX;
		while (1)
		{
			clr(vx, 0); clr(vy, 0);
			if (Find(i)) break; int a=MAX;
			rep(j, 1, n) if (!vy[j] && st[j]<a) a=st[j]; if (a==MAX) break;
			rep(j, 1, n) if (vx[j]) lx[j]-=a;
			rep(j, 1, n) if (vy[j]) ly[j]+=a; else st[j]-=a;
		}
	}
	int a=0;
	rep(i, 1, n) if (!l[i]) return 1; else a+=lx[i]+ly[i];
	return a;
}

int main()
{
	int t=read(), tt=0; while (tt++<t)
	{
		n=read(), m=read(); en=0; clr(fir, 0);
		rep(i, 1, m) { int x=read(), y=read(), z=read(); Add(x, y, -z); }
		int ans=-km(); 
		if (ans!=-1) printf("Case %d: %d\n", tt, ans); else printf("Case %d: NO\n", tt);
	}
	return 0;
} 

  

posted @ 2015-03-31 21:24  NanoApe  阅读(237)  评论(0编辑  收藏  举报
AmazingCounters.com