题目链接
http://acm.hdu.edu.cn/showproblem.php?pid=3861
题意
一个国家有n个城市,城市之间有m条单向道路。国王为了方便管理城市,决定给所有的城市分为一个州,会确保每个城市属于一个州。如果城市之间u,v之间能够相互到达,那么u,v必须分在同一个州,另外,一个州里的任意两个城市必须满足u能到v或者v能到u。求最小划分州数。
思路
tarjan缩点+二分图匹配。
最小路径覆盖=n-最大匹配。n为tarjan缩点后得到点数。这个n弄错WA了十多次。还有就是scc是全局变量,在没有调用solve前scc还没有被正确计算出来居然写出ans=scc-solve(n)( solve最后返回Hungarian() )这样的式子(╥╯^╰╥)
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<vector>
#include<string>
#include<queue>
#include<stack>
#include<set>
#include<map>
#define ll long long
using namespace std;
const int INF = ( 2e9 ) + 2;
const ll maxn = 5010;
vector<int> g1[maxn],g2[maxn];
int dfn[maxn],low[maxn],Belong[maxn],Stack[maxn];
bool Instack[maxn],vis[maxn];
int match[maxn];
int index,top,scc;
void tarjan(int u)
{
dfn[u]=low[u]=++index;
Stack[top++]=u;
Instack[u]=1;
for(int i=0,L=g1[u].size();i<L;i++)
{
int v=g1[u][i];
if(!dfn[v])
{
tarjan(v);
low[u]=min(low[u],low[v]);
}
else if(Instack[v])
low[u]=min(low[u],low[v]);
}
if(dfn[u]==low[u])
{
scc++;int x;
do
{
x=Stack[--top];
Instack[x]=0;
Belong[x]=scc;
}while(x!=u);
}
}
bool dfs(int u)
{
for(int i=0,L=g2[u].size();i<L;i++)
{
int v=g2[u][i];
if(!vis[v])
{
vis[v]=1;
if(match[v]==-1||dfs(match[v]))
{
match[v]=u;
return true;
}
}
}
return false;
}
int Hungarian()
{
int ret=0;
memset(match,-1,sizeof(match));
for(int i=1;i<=scc;i++)
{
memset(vis,0,sizeof(vis));
if(dfs(i))ret++;
}
return ret;
}
int solve(int n)
{
memset(dfn,0,sizeof(dfn));
top=scc=index=0;
for(int i=1;i<=n;i++)
if(!dfn[i])tarjan(i);
for(int i=1;i<=n;i++)
{
for(int j=0,L=g1[i].size();j<L;j++)
{
int v=g1[i][j];
if(Belong[i]!=Belong[v])
g2[Belong[i]].push_back(Belong[v]);
}
}
return scc-Hungarian();
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
int n,m,u,v;
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)
{
g1[i].clear();
g2[i].clear();
}
for(int i=0;i<m;i++)
{
scanf("%d%d",&u,&v);
g1[u].push_back(v);
}
printf("%d\n",solve(n));
}
}