POJ1422-Air Raid-二分图-DAG最小路径覆盖

题目地址  http://poj.org/problem?id=1422

二分图基础知识:http://www.cnblogs.com/HITLJR/p/5782110.html

 模板题没有思维含量,但是二分图和DAG最小路径覆盖的关系,需要仔细想明白。

代码

 1 #include <iostream>
 2 #include <cstring>
 3 #include <cstdio>
 4 
 5 using namespace std;
 6 int head[333];
 7 bool check[333];
 8 int matching[333];
 9 struct Edge
10 {
11     int to,next;
12 }E[333];
13 int ans,tot;
14 void addedge(int a,int b)
15 {
16     E[tot].to = b;
17     E[tot].next = head[a];
18     head[a] = tot++;
19 }
20 void init()
21 {
22     memset(E,0,sizeof(E));
23     memset(head,-1,sizeof(head));
24     memset(matching,-1,sizeof(matching));
25     tot = 0;
26     ans = 0;
27 }
28 bool dfs(int u)
29 {
30     for (int i = head[u] ; i!=-1 ; i = E[i].next)
31     {
32         int v = E[i].to;
33         if (!check[v])
34         {
35             check[v] = true;
36             if (matching[v] == -1 || dfs(matching[v]))
37             {
38                 matching[v] = u;
39                 matching[u] = v;
40                 return true;
41             }
42         }
43     }
44     return false;
45 }
46 int main()
47 {
48     //freopen("in.txt","r",stdin);
49     int T;
50     cin >> T;
51     while (T--)
52     {
53         init();
54         int M,N;
55         cin >> M >> N;
56         for (int i = 1 ; i <= N ; i++)
57         {
58             int a,b;
59             scanf("%d%d",&a,&b);
60             addedge(a,b+M);
61         }
62         for (int i = 1; i <= M ; i++)
63         {
64             if (matching[i] ==-1)
65             {
66                 memset(check,0,sizeof(check));
67                 if (dfs(i)) ans++;
68             }
69         }
70         cout << M - ans <<endl;
71     }
72 
73 }
原文地址:https://www.cnblogs.com/HITLJR/p/5978436.html