您的位置:首页 > 其它

HDU 1853 Cyclic Tour && HDU 3488 Tour KM算法

2015-12-03 17:53 477 查看
昨天用费用流做了这两题,今天用KM做了一下,比费用流快多了,然后,其实并不会KM算法,基本是对着百度抄的,一边抄一边理解。。。

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

const int N = 205;
const int INF = 0x3f3f3f3f;
int mpa

;
int lx
, ly
, match
, slack
;
bool visx
, visy
;
int n;

bool hungary(int v)
{
visx[v] = true;
for(int i = 1; i <= n; i++)
{
if(visy[i]) continue;
if(lx[v] + ly[i] == mpa[v][i])
{
visy[i] = true;
if(match[i] == -1 || hungary(match[i]))
{
match[i] = v;
return true;
}
}
else
slack[i] = min(slack[i], lx[v] + ly[i] - mpa[v][i]);
}

return false;
}

void km()
{
int tmp;

memset(ly, 0, sizeof ly);
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], mpa[i][j]);

for(int i = 1; i <= n; i++)
{
memset(slack, 0x3f, sizeof slack);
while(true)
{
memset(visx, 0, sizeof visx);
memset(visy, 0, sizeof visy);

if(hungary(i)) break;
else
{
tmp = INF;
for(int j = 1; j <= n; j++)
if(! visy[j])
tmp = min(tmp, slack[j]);
for(int j = 1; j <= n; j++)
{
if(visx[j]) lx[j] -= tmp;
if(visy[j]) ly[j] += tmp;
else slack[j] -= tmp;
}
}
}
}
}

int main()
{
int t, m;
int a, b, c;

scanf("%d", &t);
while(t--)
{
scanf("%d%d", &n, &m);
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++)
mpa[i][j] = -INF;

for(int i = 0; i < m; i++)
{
scanf("%d%d%d", &a, &b, &c);
if(mpa[a][b] < -c)
mpa[a][b] = -c;
}

memset(match, -1, sizeof match);
km();

bool f = true;
int res = 0;
for(int i = 1; i <= n; i++)
{
if(match[i] == -1 || mpa[match[i]][i] == -INF)
{
f = false;
break;
}
res += mpa[match[i]][i];
}

if(f) printf("%d\n", -res);
else printf("-1\n");
}

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