1. 程式人生 > >hdu 1151 Air Raid (最小路徑覆蓋)

hdu 1151 Air Raid (最小路徑覆蓋)

最小路徑覆蓋

求出最大匹配,用頂點數減去即可。。

//
//  main.cpp
//  wzazzy
//
//  Created by apple on 2018/10/23.
//  Copyright © 2018年 apple. All rights reserved.
//

#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<string.h>
#include<queue>
#include<stack>
#include<list>
#include<map>
#include<set>
#include<vector>
using namespace std;
typedef long long int ll;
const int maxn =1500+10;
const int maxm=10000;
const int mod =1e9+7;
const int INF=0x3f3f3f3f;
//**********************************
struct Edge
{
    int to,next;
}edge[maxn];
int head[maxn],tot;
void init()
{
    tot=0;
    memset(head,-1,sizeof(head));
}
void addedge(int u,int v)
{
    edge[tot].to=v;edge[tot].next=head[u];
    head[u]=tot++;
}
int linker[maxn];
bool used[maxn];
int uN;
bool dfs(int u)
{
    for(int i=head[u];i!=-1;i=edge[i].next)
    {
        int v=edge[i].to;
        if(!used[v])
        {
            used[v]=true;
            if(linker[v]==-1||dfs(linker[v]))
            {
                linker[v]=u;
                return true;
            }
        }
    }
    return false;
}
int hungary()
{
    int res=0;
    memset(linker,-1,sizeof(linker));
    for(int u=0;u<uN;u++)
    {
        memset(used,false,sizeof(used));
        if(dfs(u)) res++;
    }
    return res;
}
int main(int argc,const char * argv[])
{
    int t;scanf("%d",&t);
    while(t--)
    {
        int n,m;scanf("%d%d",&n,&m);
        init();
        uN=n;
        for(int i=0;i<m;i++)
        {
            int u,v;scanf("%d%d",&u,&v);
            u--,v--;
            addedge(u,v);
        }
        printf("%d\n",n-hungary());
    }
    return 0;
}