4883: [Lydsy2017年5月月赛]棋盘上的守卫

来源:互联网 发布:seo诊断seo8 编辑:程序博客网 时间:2024/06/06 20:39

4883: [Lydsy2017年5月月赛]棋盘上的守卫

Time Limit: 3 Sec Memory Limit: 256 MB
Submit: 143 Solved: 70
[Submit][Status][Discuss]
Description

在一个n*m的棋盘上要放置若干个守卫。对于n行来说,每行必须恰好放置一个横向守卫;同理对于m列来说,每列
必须恰好放置一个纵向守卫。每个位置放置守卫的代价是不一样的,且每个位置最多只能放置一个守卫,一个守卫
不能同时兼顾行列的防御。请计算控制整个棋盘的最小代价。
Input

第一行包含两个正整数n,m(2<=n,m<=100000,n*m<=100000),分别表示棋盘的行数与列数。
接下来n行,每行m个正整数
其中第i行第j列的数w[i]j表示在第i行第j列放置守卫的代价。
Output

输出一行一个整数,即占领棋盘的最小代价。
Sample Input

3 4

1 3 10 8

2 1 9 2

6 7 4 6
Sample Output

19

HINT

在(1,1),(2,2),(3,1)放置横向守卫,在(2,1),(1,2),(3,3),(2,4)放置纵向守卫。
HINT

Source

鸣谢Claris上传试题

[Submit][Status][Discuss]

把棋子看成个边,行和列看成点
于是就有了一张nm个点和nm条边的图
显然,一组合法解中,每个连通块都是一棵环套树
因为都是N个点N条边,多一条则无法配对
那么用kruscal算法解决就行了

#include<iostream>#include<cstdio>#include<algorithm>using namespace std;const int maxn = 1E5 + 10;typedef long long LL;struct E{    int x,y,w; E(){}    E(int x,int y,int w): x(x),y(y),w(w){}    bool operator < (const E &B) const {return w < B.w;}}edgs[maxn];int n,m,tot,cnt,fa[maxn];bool bo[maxn]; LL Ans;inline int getfa(int k) {return k == fa[k] ? k : fa[k] = getfa(fa[k]);}inline int getint(){    char ch = getchar(); int ret = 0;    while (ch < '0' || '9' < ch) ch = getchar();    while ('0' <= ch && ch <= '9')        ret = ret * 10 + ch - '0',ch = getchar();    return ret;}int main(){    #ifdef DMC        freopen("DMC.txt","r",stdin);    #endif    n = getint(); m = getint();    for (int i = 1; i <= n; i++)        for (int j = 1; j <= m; j++)        {            int w = getint();            edgs[++cnt] = E(i,j + n,w);        }    sort(edgs + 1,edgs + cnt + 1);    for (int i = 1; i <= n + m; i++) fa[i] = i;    for (int i = 1; i <= cnt; i++)    {        E &e = edgs[i];        int fx = getfa(e.x),fy = getfa(e.y);        if (bo[fx] && bo[fy]) continue;        if (fx != fy)        {            Ans += 1LL * e.w; ++tot;            fa[fx] = fy; bo[fy] |= bo[fx];        }        else        {            if (bo[fx]) continue;            bo[fx] = 1; Ans += 1LL * e.w; ++tot;        }        if (tot == n + m) break;    }    cout << Ans << endl;    return 0;}
原创粉丝点击