标签:
KM模版题。
#include <cstdlib> #include <cmath> #include <cstdio> #include <cstring> #include <algorithm> #include <fstream> #include <iostream> #define rep(i, l, r) for(int i=l; i<=r; i++) #define N 345 #define clr(x, c) memset(x, c, sizeof(x)); #define ll long long #define MAX 1<<30 using namespace std; int read() { int x=0, f=1; char ch=getchar(); while (ch<‘0‘ || ch>‘9‘) { if (ch==‘-‘) f=-1; ch=getchar(); } while (ch>=‘0‘ && ch<=‘9‘) { x=x*10+ch-‘0‘; ch=getchar(); } return x*f; } int n, nx, ny, lx[N], ly[N], v[N][N], l[N], st[N]; bool vx[N], vy[N]; bool Find(int x) { vx[x]=1; rep(y, 1, ny) if (!vy[y]) { int a=lx[x]+ly[y]-v[x][y]; if (!a) { vy[y]=1; if (!l[y] || Find(l[y])) { l[y]=x; return true; } } else st[y]=min(st[y], a); } return false; } int KM() { rep(i, 1, nx) lx[i]=-MAX; clr(ly, 0); clr(l, 0); rep(i, 1, nx) rep(j, 1, ny) if (lx[i]<v[i][j]) lx[i]=v[i][j]; rep(i, 1, nx) { rep(j, 1, ny) st[j]=MAX; while (1) { clr(vx, 0); clr(vy, 0); if (Find(i)) break; int a=MAX; rep(j, 1, ny) if (!vy[j] && a>st[j]) a=st[j]; rep(j, 1, nx) if (vx[j]) lx[j]-=a; rep(j, 1, ny) if (vy[j]) ly[j]+=a; else st[j]-=a; } } int ans=0; rep(i, 1, nx) if (l[i]) ans+=v[l[i]][i]; return ans; } int main() { while (~scanf("%d", &n)) { nx=ny=n; rep(i, 1, nx) rep(j, 1, ny) v[i][j]=read(); printf("%d\n", KM()); } return 0; }
标签:
原文地址:http://www.cnblogs.com/NanoApe/p/4382046.html