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; }
相关文章推荐
- 小乐乐想下山HLG
- 小乐乐想出门HLG
- Android动态换肤开源库Colorful发布
- ln 命令
- git 常用命令
- Mysql存储过程和函数
- [leetcode:13] 罗马数字转十进制
- Motion Detection
- BLE HID:HOGP 设备开发指引
- samba configure on Cent OS 6.4
- Ring实现原理剖析
- jQuery实现手机上输入后隐藏键盘
- int main(int argc,char *argv[]),主函数的参数问题
- 直接通过SQL能查到,通过HSQL查询不到问题解决
- AuidioStreamPlayer简易实现
- 无界通配符、有界通配符、extends可取、super可存
- 小乐乐大逃亡HLG
- 告警信息大爆炸,运维解放秘籍!
- 推送通知,非常详细
- iOS常用宏定义