hdu 4635 Strongly connected

先根据trajan算法找出连通分量缩点,然后得出一个新的不存在连通分量的有向图,然后查找有向图中出度或者入度为零的点,然后根据这个点的点数(如果是连通图缩成的点就不是一个点了)x,以及剩下的点数y=n-x,那么 sum = max( (x-1)*x+y*(y-1)+x*y-m ,sum )就是所能加的最大边数

#include <cstdio>
#include <cstring>
#include <vector>
#include <stack>
#include <algorithm>
using namespace std;
#define N 100010
#define LL long long
stack<int> s;
vector<int> G[N];
int dfs_clock,scc_cnt;
LL sum;
int sccno[N],pre[N],cnt[N],in[N],out[N];
int dfs(int u)
{
    int lowu=pre[u]=++dfs_clock;
    s.push(u);
    for(int i=0; i<G[u].size(); ++i)
    {
        int v=G[u][i];
        if(!pre[v])
        {
            int lowv=dfs(v);
            lowu=min(lowu,lowv);
        }
        else if(!sccno[v]) lowu=min(lowu,pre[v]);
    }
    if(pre[u]==lowu)
    {
        ++scc_cnt;
        int c=0;
        while(1)
        {
            ++c;
            int x=s.top();
            s.pop();
            sccno[x]=scc_cnt;
            if(x==u) break;
        }
        cnt[scc_cnt]=c;
    }
    return lowu;
}
void find_scc(int n)
{
    dfs_clock=scc_cnt=0;
    sum=0;
    for(int i=0; i<n; ++i) sccno[i]=pre[i]=cnt[i]=in[i]=out[i]=0;
    for(int i=0; i<n; ++i)
        if(!pre[i]) dfs(i);
}

int main()
{
    //freopen("in.txt","r",stdin);
    int n,m,t,p=1;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d%d",&n,&m);
        for(int i=0; i<n; ++i) G[i].clear();
        int x,y;
        for(int i=0; i<m; ++i)
        {
            scanf("%d%d",&x,&y);
            G[x-1].push_back(y-1);
        }
        find_scc(n);
        if(scc_cnt==1)
        {
            printf("Case %d: -1\n",p++);
            continue;
        }
        for(int i=0; i<n; ++i)
            for(int j=0; j<G[i].size(); ++j)
                if(sccno[i]!=sccno[G[i][j]]) ++in[sccno[G[i][j]]],++out[sccno[i]];
        for(int i=1; i<=scc_cnt; ++i)
            if(!in[i]||!out[i])
            {
                LL x=cnt[i],y=n-cnt[i];
                sum=max(sum,x*(x-1)+(y-1)*y+x*y-m);
            }
        printf("Case %d: %I64d\n",p++,sum);
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值