题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3861
题意:给出一张N个点M条边的有向图,要求划分出的区域最少,划分规则满足:
1.(u, v)互相可达,则u,v两点必须在同一区域
2.若(u, v)两点有一个可达另一个,则可划在同一区域,也可不划
3.每个点只属于一个区域
思路:对于1条件,则强连通内的点必在同一区域,故先强连通缩点,然后对于缩点后的图考虑条件2,这就相当于求这些连通分量的最小路径覆盖,转为二分图模型求解,注意编号问题
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
#include <utility>
#include <cmath>
#include <queue>
#include <set>
#include <map>
#include <climits>
#include <functional>
#include <deque>
#include <ctime>
#include <string>
#define lson l, mid, rt << 1
#define rson mid + 1, r, rt << 1 | 1
#pragma comment(linker, "/STACK:102400000,102400000")
using namespace std;
const int MAXN = 10010;
const int MAXM = 200010;
int head[MAXN], tot;
int Low[MAXN], DFN[MAXN], Stack[MAXN], Belong[MAXN];
int Index, top, scc;
bool Instack[MAXN];
int num[MAXN];
struct Edge
{
int to, next;
} edge[MAXM];
void addedge(int u, int v)
{
edge[tot].to = v;
edge[tot].next = head[u];
head[u] = tot++;
}
void Tarjan(int u)
{
int v;
Low[u] = DFN[u] = ++Index;
Stack[top++] = u;
Instack[u] = true;
for (int i = head[u]; i != -1; i = edge[i].next)
{
v = edge[i].to;
if (!DFN[v])
{
Tarjan(v);
if ( Low[u] > Low[v] )Low[u] = Low[v];
}
else if (Instack[v] && Low[u] > DFN[v])
Low[u] = DFN[v];
}
if (Low[u] == DFN[u])
{
scc++;
do
{
v = Stack[--top];
Instack[v] = false;
Belong[v] = scc;
num[scc]++;
}
while (v != u);
}
}
void solve(int N)
{
memset(DFN, 0, sizeof(DFN));
memset(Instack, false, sizeof(Instack));
memset(num, 0, sizeof(num));
Index = scc = top = 0;
for (int i = 1; i <= N; i++)
if (!DFN[i])
Tarjan(i);
}
void init()
{
tot = 0;
memset(head, -1, sizeof(head));
}
vector <int> g[MAXN];
int match[MAXN], vis[MAXN];
int sum;
void add(int u, int v)
{
g[u].push_back(v);
g[v].push_back(u);
}
bool dfs(int v)
{
vis[v] = 1;
for (int i = 0; i < g[v].size(); i++)
{
int u = g[v][i], w = match[u];
if (w < 0 || (!vis[w] && dfs(w)))
{
match[v] = u;
match[u] = v;
return true;
}
}
return false;
}
int hungary()
{
int res = 0;
memset(match, -1, sizeof(match));
for (int v = 0; v < sum; v++)
{
if (match[v] < 0)
{
memset(vis, 0, sizeof(vis));
if (dfs(v))
res++;
}
}
return res;
}
int main()
{
int t;
scanf("%d", &t);
while (t--)
{
int n, m;
scanf("%d%d", &n, &m);
init();
for (int i = 0; i < m; i++)
{
int u, v;
scanf("%d%d", &u, &v);
addedge(u, v);
}
solve(n);
sum = scc * 2;
for (int i = 0; i <= sum; i++) g[i].clear();
for (int u = 1; u <= n; u++)
for (int j = head[u]; ~j; j = edge[j].next)
{
int v = edge[j].to;
if (Belong[u] != Belong[v])
add(Belong[u] - 1, Belong[v] - 1 + n);
}
cout << scc - hungary() << endl;
}
return 0;
}