Bullet
Description
In GGO, a world dominated by gun and steel, players are fighting for the honor of being the strongest gunmen. Player Shino is a sniper, and her aimed shot kills one monster at a time. Now she is in an n×n map, and there are monsters in some grids. Each monster has an experience. As a master, however, Shino has a strange self-restrain. She would kill at most one monster in a column, and also at most one in a row. Now she wants to know how to get max experience, under the premise of killing as many monsters as possible.
Input
The first line contains an integer n(n≤500)
Then n lines follow. In each line there are n integers, and Aijrepresents the experience of the monster at grid(i,j). If Aij=0, there is no monster at grid(i,j).
Aij≤109
Output
One integer, the value of max experience.
Samples
Input
2
2 0
1 8
Output
2
题意:
每行只可以选一个怪物,每列也只能选一个怪物,问你在可选最多怪物的前提下,最小的经验是多少。
思路:显然是个二分图裸题,把行和列分成两组,若Aij非零,则在i行j列之间连起一条边。可用最大流,建立源点s,汇点t,把图建立起来,跑最大流即求出最大匹配。
Code:
#include<bits/stdc++.h>
#define bug(x) cout<<#x<<" = "<<x<<endl;
using namespace std;
typedef long long ll;
const int M = 1e6 + 10;
const int N = 5e3 + 10;
const int inf = 1e9;
struct Node {
int to,next,val;
} e[M];
int n,m,s,t;
int cnt=1; //可用 ^运算找出反边
int head[N],a[550][550],dep[N],maxx;
bool vis[N];
void add_edge(int u,int v,int w) {
cnt++;
e[cnt].to = v;
e[cnt].val = w;
e[cnt].next = head[u];
head[u] = cnt;
}
bool bfs() {
memset(dep,0,sizeof(dep));
queue<int> q;
q.push(s);
dep[s] = 1;
while(q.size()) {
int u = q.front();
q.pop();
for(int i=head[u]; i; i=e[i].next) {
int v = e[i].to;
if(e[i].val&&!dep[v]) {
dep[v] = dep[u] + 1;
q.push(v);
}
}
}
return dep[t];
}
int dfs(int u,int in) {
if(u==t) return in;
int out=0;
for(int i=head[u]; i; i=e[i].next) {
int v = e[i].to;
if(e[i].val&&dep[v] == dep[u] + 1) {
int w = dfs(v,min(in,e[i].val));
if(w) {
e[i].val -= w;
e[i^1].val += w;
out += w;
in -= w;
if(!in) return out;
} else dep[v] = 0;
}
}
return out;
}
bool work(int midd,bool ff) {
memset(head,0,sizeof(head));
cnt = 1;
for(int i=1; i<=n; i++) {
add_edge(s,i,1);
add_edge(i,s,0);
add_edge(i+n,t,1);
add_edge(t,i+n,0);
}
for(int i=1; i<=n; i++) {
for(int j=1; j<=n; j++) {
if(a[i][j]>=midd) add_edge(i,j+n,1),add_edge(j+n,i,0);
}
}
int res = 0;
while(bfs()) {
res += dfs(s,1e9);
}
//bug(res);
if(ff) {
maxx = res;
return 1;
} else return res == maxx;
}
int main() {
scanf("%d",&n);
s = 0;
t = 2*n+1;
for(int i=1; i<=n; i++) for(int j=1; j<=n; j++) scanf("%d",&a[i][j]);
work(1,1);
int l=1,r=1e9,ans=0;
while(l<=r) {
int mid = (l+r) >> 1;
if(work(mid,0)) ans=mid,l=mid+1;
else r=mid-1;
}
cout<<ans;
return 0;
}
/*
*/