敲了一周高校联盟比赛的我决定转战bzoj

本文分享了解决洛谷图论题目P2002的经验,通过记录节点入度并使用Tarjan算法进行缩点,最终成功通过了该题目。文章详细介绍了Tarjan算法的实现过程。

高校联盟比赛成绩差一等线30分  (我弱)

坚定了我的信心微笑

接下来把洛谷团队里的图论题打完就差不多好走人了

今天随意搞了一道洛谷图论题 p2002

一开始就直接记下入度

然后for一边遇到入度为0的ans++

然后就70

后面发现bug

然后就打了一个 tarjan缩点 就AC了

#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <stack>
#include <cmath>
#define maxn 500005
using namespace std;
int topt,n,m,next[maxn],to[maxn],st[maxn],xx,yy,dfn[maxn],low[maxn],be[maxn],in[maxn];
int num,scc[maxn],ans;
bool f[maxn];
void add(int x,int y)
{
    to[++topt]=y;
    next[topt]=st[x];
    st[x]=topt;
}
stack<int>s;
void tarjan(int x)
{
    dfn[x]=low[x]=++topt;
    s.push(x); f[x]=1;
    int p=st[x];
    while (p)
    {
        if (!dfn[to[p]]) {tarjan(to[p]); low[x]=min(low[x],low[to[p]]);}
         else if (f[to[p]]) low[x]=min(low[x],dfn[to[p]]);
        p=next[p];
    }
    if (dfn[x]==low[x])
    {
        num++;
        while (s.top()!=x)
        {
            f[s.top()]=0;
            scc[s.top()]=num;
            s.pop();
        }
        f[s.top()]=0; scc[s.top()]=num; s.pop();
    } 
}
int main()
{
    scanf("%d%d",&n,&m);
    for (int i=1;i<=m;i++) 
     {scanf("%d%d",&xx,&yy); add(xx,yy);}
    topt=0;
    for (int i=1;i<=n;i++)
     if (!dfn[i]) tarjan(i);
    for (int i=1;i<=n;i++)
    {
        int p=st[i];
        while (p)
        {
            if (scc[i]!=scc[to[p]]) in[scc[to[p]]]++;
            p=next[p];
        }
    }
    for (int i=1;i<=num;i++)
     if (in[i]==0) ans++;
    printf("%d\n",ans);
return 0;


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值