HDU 3861 The King’s Problem 强连通缩点+最小路径覆盖

题目链接

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));
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值