标签:oid ace line mat 超级 inline ++ void namespace
我们将每行看做\(X\)顶点,将每列看做\(Y\)顶点.原来行与列的交点就变成\(X\),\(Y\)顶点之间的边.那么原来的网格图就被转化成了一个二分图
所以这道题就是是一道二分图最小顶点覆盖的模板题了,只不过输出方案比较恶心而已.关于何为二分图最小顶点覆盖,本文不再赘述
关于二分图最小顶点覆盖,我们有一个定理,即二分图最小顶点覆盖等于最大匹配,下面给出一个简短的证明
设最大匹配为\(n\),那么
运用这个定理,我们可以很轻松的求出最小需要的炮弹数,但是怎么输出方案呢?
如果不算与附加源汇相连的附加弧,需要计入答案的无非这几种情况:
从源点开始搜索,但是不经过满流的边
那么需要打炮弹的顶点就是以下情况了:
代码如下:
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
const int maxn = 2048;
const int maxm = (1001024 + maxn) << 1;
struct Edge{
int from,to,cap,flow;
Edge() = default;
Edge(int a,int b,int c,int d):from(a),to(b),cap(c),flow(d){}
}Edges[maxm];
int head[maxn],nxt[maxm],tot = 1;
inline void clear(){
memset(head,0,sizeof(head));
memset(nxt,0,sizeof(nxt));
tot = 1;
}
inline void addedge(int from,int to,int cap){
Edges[++tot] = Edge(from,to,cap,0);
nxt[tot] = head[from];
head[from] = tot;
Edges[++tot] = Edge(to,from,0,0);
nxt[tot] = head[to];
head[to] = tot;
}
int d[maxn];
inline bool bfs(int s,int t){
memset(d,-1,sizeof(d)),d[s] = 0;
queue<int> Q;
Q.push(s),d[s] = 0;
while(!Q.empty()){
int u = Q.front();Q.pop();
for(int i = head[u];i;i = nxt[i]){
Edge &e = Edges[i];
if(e.cap > e.flow && d[e.to] == -1)
d[e.to] = d[e.from] + 1,Q.push(e.to);
}
}
return d[t] != -1;
}
int cur[maxn];
inline int dfs(int u,int a,int t){
if(u == t || a == 0)return a;
int ret = 0,f;
for(int &i = cur[u];i;i = nxt[i]){
Edge &e = Edges[i];
if(d[u] + 1 == d[e.to] && (f = dfs(e.to,min(a,e.cap - e.flow),t)) > 0){
ret += f;
Edges[i].flow += f;
Edges[i ^ 1].flow -= f;
a -= f;
if(a == 0)break;
}
}
return ret;
}
inline int maxflow(int s,int t){
int ret = 0;
while(bfs(s,t)){
memcpy(cur,head,sizeof(head));
ret += dfs(s,0x7fffffff,t);
}
return ret;
}
int vis[maxn],apr[maxn];
inline void find(int u){
vis[u] = 1;
for(int i = head[u];i;i = nxt[i]){
Edge &e = Edges[i];
if(e.flow == e.cap || vis[e.to])continue;
find(e.to);
}
}
int n,m,r;
inline void solve(){
clear();
memset(apr,0,sizeof(apr));
for(int x,y,i = 1;i <= r;i++)
scanf("%d %d",&x,&y),addedge(x,n + y,1),apr[x] = apr[n + y] = 1;
int s = n + m + 1,t = n + m + 2;
for(int i = 1;i <= n;i++)
addedge(s,i,1);
for(int i = n + 1;i <= n + m;i++)
addedge(i,t,1);
memset(vis,0,sizeof(vis));
printf("%d",maxflow(s,t));
find(s);
for(int i = 1;i <= n;i++)if(apr[i] && !vis[i])printf(" r%d",i);
for(int i = n + 1;i <= n + m;i++)if(apr[i] && vis[i])printf(" c%d",i - n);
printf("\n");
}
int main(){
#ifdef LOCAL
freopen("fafa.in","r",stdin);
#endif
while(scanf("%d %d %d",&n,&m,&r) && (n || m || r))
solve();
return 0;
}
标签:oid ace line mat 超级 inline ++ void namespace
原文地址:https://www.cnblogs.com/colazcy/p/11515004.html