poj 2594

来源:互联网 发布:sql注入漏洞的原理 编辑:程序博客网 时间:2024/06/08 06:34

与直接的最小覆盖不相同的是,本题最小路径上的点可以重复访问,即需要用Floyd重新构图,然后再求最小覆盖。


#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;


const int MAXN = 1005;
bool map[MAXN][MAXN];
bool visy[MAXN];
int match[MAXN];
int n1,n2;//x集合的个数,y集合的个数


bool DFS(int x)
{
    for(int i = 1;i<=n2;i++)
    {
        if(!visy[i]&&map[x][i])
        {
            visy[i] = true;
            if(match[i]==-1||DFS(match[i]))
            {
                match[i] = x;
                return true;
            }
        }
    }
    return false;
}


void Floyd(int n)
{
    for(int k = 1;k<=n;k++)
        for(int i = 1;i<=n;i++)
            for(int j = 1;j<=n;j++)
            {
                if(map[i][k]+map[k][j]>1)
                {
                    map[i][j] = 1;
                }
            }
}


int main()
{
    int n,m,u,v;
    while(scanf("%d %d",&n,&m)&&(m||n))
    {
        n1 = n2 = n;
        memset(match,-1,sizeof(match));
        memset(map,0,sizeof(map));
        for(int i = 0;i<m;i++)
        {
            scanf("%d %d",&u,&v);
            map[u][v] = 1;
        }
        Floyd(n);
        int ans = 0;
        for(int i = 1;i<=n;i++)
        {
            memset(visy,0,sizeof(visy));
            if(DFS(i)) ans++;
        }
        printf("%d\n",n-ans);
    }
    return 0;
}