Description
在一个n*m的棋盘上要放置若干个守卫。对于n行来说,每行必须恰好放置一个横向守卫;同理对于m列来说,每列
必须恰好放置一个纵向守卫。每个位置放置守卫的代价是不一样的,且每个位置最多只能放置一个守卫,一个守卫
不能同时兼顾行列的防御。请计算控制整个棋盘的最小代价。
2<=n,m<=100000,n*m<=100000
1<=w[i][j]<=10^9 表示在第i行第j列放置守卫的代价。
Solution
把一个格点看成是连接行和列的边,那么我们需要找一个子图使得n+m个点都恰好出现一次,即把边定向后每个点入度为1,且边权和最小。可以发现这样的子图一定是环套树森林
那么可以用并查集维护一个连通的子图,按边权排序一下每次合并一条边的两端时特判一下就好了
其实题意更像是费用流,但是复杂度十分玄学估计卡不过去
Code
#include <stdio.h>
#include <string.h>
#include <algorithm>
#define rep(i,st,ed) for (int i=st;i<=ed;++i)
typedef long long LL;
const int N=400005;
int fa[N],vis[N];
struct edge {int x,y,w;} e[N*2];
int read() {
int x=0,v=1; char ch=getchar();
for (;ch<'0'||ch>'9';v=(ch=='-')?(-1):(v),ch=getchar());
for (;ch<='9'&&ch>='0';x=x*10+ch-'0',ch=getchar());
return x*v;
}
bool cmp(edge a,edge b) {
return a.w<b.w;
}
int get_father(int x) {
if (!fa[x]) return x;
return fa[x]=get_father(fa[x]);
}
int main(void) {
int n=read(),m=read();
rep(i,1,n) rep(j,1,m) {
e[(i-1)*m+j]=(edge) {i,j+n,read()};
}
std:: sort(e+1,e+n*m+1,cmp);
LL ans=0;
rep(i,1,n*m) {
int fx=get_father(e[i].x);
int fy=get_father(e[i].y);
if (fx==fy) {
if (!vis[fx]) {
vis[fx]=1;
ans+=e[i].w;
}
} else if (!vis[fx]||!vis[fy]) {
fa[fx]=fy;
ans+=e[i].w;
vis[fy]|=vis[fx];
}
}
printf("%lld\n", ans);
return 0;
}