hdu1498二分图最小顶点覆盖

来源:互联网 发布:mac photo collage 编辑:程序博客网 时间:2024/05/16 19:16

题意:有一个n*n的气球阵,每一次可以将任意一行或一列中相同颜色的气球打破,一共有k次机会,问有哪种颜色的气球不能在k次内全部打破。 气球种类最多有60种。
建图后题意就是,将列看做二分图左集合,行看做右集合,用不同的颜色连线,问每一种颜色的最小顶点覆盖是否不大于k。

比如说:
4 2
1 2 3 4
1 2 4 3
2 2 1 3
1 4 3 1 这组数据 输出是 1 4。
颜色2 需要2次分别是第一列、第二列 ,颜色3需要2次第三列、第四列。
而颜色1和颜色4不能在2次能全部打破。

思路:
1、对于每一种颜色的气球,能不能在k次内被打破和其他颜色的气球是没有任何关系的。所以需要对每一种颜色进行枚举。

2、针对某一种颜色col的气球时,就是看最少需要多少个列和行可以将所有的col这个颜色的气球覆盖完,那么,将列看做一个集合,行看做一个集合,如果第i行,第j列有col的气球,则从i到j连一条线。二分图建好了,求最小顶点覆盖。

#include <iostream>#include <cstring>#include <cstdio>#include <set>using namespace std;const int maxn = 55;int n,k;int match[maxn],vis[maxn]; //存求解结果int Map[maxn][maxn];bool dfs(int u, int col){    for(int i=1; i<=n; i++)    {        if(!vis[i] && Map[u][i] == col) //模板中需要改动的        {            vis[i] = 1;            if(match[i] == -1 || dfs(match[i],col))            {                match[i] = u;                return true;            }        }    }    return false;}int hungry(int col){    memset(match, -1, sizeof(match));    int ans = 0;    for(int i=1; i<=n; i++)    {        memset(vis, 0, sizeof(vis));        if(dfs(i,col))            ans++;    }    return ans;}int main(){    while(scanf("%d%d",&n,&k) != EOF && n)    {        set<int> color;        memset(Map, 0, sizeof(Map));        for(int i=1; i<=n; i++)        {            for(int j=1; j<=n; j++)            {                scanf("%d",&Map[i][j]); //建图                color.insert(Map[i][j]); //自动排序且不会有重复的            }        }        bool isone=1, nofind=1;        for(set<int>::iterator it=color.begin(); it!=color.end(); it++)        {            if(hungry(*it) > k)            {                nofind = 0;                if(isone) //输出格式                {                    printf("%d",*it);                    isone = 0;                }                else                    printf(" %d",*it);            }        }        if(nofind)            printf("-1");        printf("\n");    }    return 0;}
原创粉丝点击