您的位置:首页 > 其它

HDU 3435 KM A new Graph Game

2015-09-05 10:39 344 查看
和HDU 3488一样的,只不过要判断一下是否有解。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;

const int maxn = 1000 + 10;
const int INF = 0x3f3f3f3f;

int n, m;

int W[maxn][maxn], lft[maxn];
int slack[maxn];
int Lx[maxn], Ly[maxn];
bool S[maxn], T[maxn];

bool match(int u)
{
S[u] = true;
for(int v = 1; v <= n; v++) if(!T[v])
{
int t = Lx[u] + Ly[v] - W[u][v];
if(0 == t)
{
T[v] = true;
if(!lft[v] || match(lft[v]))
{
lft[v] = u;
return true;
}
}
else slack[v] = min(slack[v], t);
}

return false;
}

void update()
{
int a = INF;
for(int i = 1; i <= n; i++) if(!T[i]) a =  min(a, slack[i]);
for(int i = 1; i <= n; i++)
{
if(S[i]) Lx[i] -= a;

if(T[i]) Ly[i] += a;
else  slack[i] -= a;
}
}

void KM()
{
memset(Ly, 0, sizeof(Ly));
memset(lft, 0, sizeof(lft));
for(int i = 1; i <= n; i++) Lx[i] = -INF;
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++) Lx[i] = max(Lx[i], W[i][j]);

for(int i = 1; i <= n; i++)
{
memset(slack, 0x3f, sizeof(slack));
for(;;)
{
memset(S, false, sizeof(S));
memset(T, false, sizeof(T));
if(match(i)) break;
update();
}
}
}

int main()
{
int T; scanf("%d", &T);
for(int kase = 1; kase <= T; kase++)
{
scanf("%d%d", &n, &m);
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++)
W[i][j] = -INF;
for(int i = 0; i < m; i++)
{
int u, v, d; scanf("%d%d%d", &u, &v, &d);
if(W[u][v] < -d) W[u][v] = W[v][u] = -d;
}

KM();

bool ok = true;
int ans = 0;
for(int i = 1; i <= n; i++)
{
if(W[lft[i]][i] == -INF) { ok = false; break; }
ans += W[lft[i]][i];
}
printf("Case %d: ", kase);
if(!ok) puts("NO");
else printf("%d\n", -ans);
}

return 0;
}


代码君
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: