題目:http://acm.hdu.edu.cn/showproblem.php?pid=3861
題意:王國劃分區域,每個城市間的路是有方向的,要求每個區域滿足:1.存在環路的必定在一個區域內。2.一個區域中的城市必定滿足兩兩之間有一個可以到達另一個,求可以劃分的區域數
題解:對於第一個條件即是要求出圖中的環路縮點,即用tarjan算法進行強連通分量的計算,對於第二個條件即是求最小路徑覆蓋(匈牙利算法)
代碼:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<vector>
using namespace std;
const int MAX=5555;
int dfn[MAX],low[MAX],belong[MAX],time;
int cont;
bool instack[MAX];
int _stack[MAX],top;
vector<int> dian[MAX];
int match[MAX];
bool vis[MAX];
vector<int> newv[MAX];
void tarjan(int root)
{
dfn[root]=low[root]=time++;
_stack[top++]=root;
instack[root]=true;
for(int i=0;i<dian[root].size();i++)
{
int son=dian[root][i];
if(!dfn[son])
{
tarjan(son);
low[root]=min(low[root],low[son]);
}
else if(instack[son])
{
low[root]=min(low[root],dfn[son]);
}
}
if(dfn[root] == low[root])
{
int v;
do
{
v=_stack[--top];
instack[v]=false;
belong[v]=cont;
}
while(root!=v);
cont++;
}
}
void init_tarjan(int n)
{
memset(dfn,0,sizeof(dfn));
memset(instack,false,sizeof(instack));
top=time=cont=1;
for(int i=1;i<=n;i++)
{
if(dfn[i]==0) tarjan(i);
}
}
bool dfs(int root)
{
for(int i=0;i<newv[root].size();i++)
{
int v=newv[root][i];
if(!vis[v])
{
vis[v]=true;
if(match[v]==-1 || dfs(match[v]))
{
match[v]=root;
return true;
}
}
}
return false;
}
int main()
{
int t;
int n,m;
scanf("%d",&t);
while(t--)
{
scanf("%d %d",&n,&m);
for(int i=1;i<=m;i++)
{
int s,e;
scanf("%d %d",&s,&e);
dian[s].push_back(e);
}
init_tarjan(n);
for(int i=1;i<=n;i++)
{
int u=belong[i];
for(int j=0;j<dian[i].size();j++)
{
int v=belong[dian[i][j]];
if(u!=v) newv[u].push_back(v);
}
}
int ans=0;
memset(match,-1,sizeof(match));
for(int i=1;i<cont;i++)
{
memset(vis,false,sizeof(vis));
ans+=dfs(i);
}
printf("%d\n",cont-1-ans);
for(int i=1;i<=n;i++)
{
newv[i].clear();
dian[i].clear();
}
}
return 0;
}