信息传递 LibreOJ - 2421(tarjan,求每个环的min)

信息传递 LibreOJ - 2421

题意:

给你n个人。每个人会向 T i T_i Ti传递信息。

最少经过多少轮后,会有人搜到自己的电话。

思路:

  1. 其实就是求强联通分量时,把每个环的长度取个min。

AC

#include <iostream>
#include <cstdio>
#include <cstring>
#include <stack>
#define For(i,x,y) for(int i=(x); i<=(y); i++)
#define fzhead EDGE(int _to, int _next)
#define fzbody to(_to), next(_next)
#define mst(x,a) memset(x,a,sizeof(x))
#pragma comment(linker,"STACK:102400000,102400000")
using namespace std;
const int maxn=2e5+10;
const int inf = 1e9+10;
struct EDGE{
    int to,next;
    EDGE(){}
    fzhead:fzbody{}
}e[2*maxn];
int tot,head[maxn],vis[maxn];
void add(int bg, int to){
    e[tot]=EDGE(to,head[bg]);
    head[bg]=tot++;
}
int dfn[maxn],low[maxn];
int dfs_clock,bcc_cnt;
int ans,n;
stack<int>s;
void init(){
    ans=inf;
    dfs_clock=bcc_cnt=tot=0;
    mst(head,-1);
    mst(vis,0);
    mst(dfn,0);
    mst(low,0);
    while(!s.empty())s.pop();
}
void tarjan(int u){
    vis[u]=1;
    dfn[u]=low[u]=++dfs_clock;
    s.push(u);
    for(int i=head[u]; i!=-1; i=e[i].next){
        int v=e[i].to;
        if(!dfn[v]){
            tarjan(v);
            low[u]=min(low[u],low[v]);
        }else if(vis[v]){
            if(dfn[v]<dfn[u])ans=min(ans,dfn[u]-dfn[v]+1);
            low[u]=min(low[u],dfn[v]);
        }
    }
    if(dfn[u]==low[u]){
        vis[u]=0;
        int j;
        do{
            j=s.top();s.pop();
        }while(j!=u);
    }
}
int main()
{
    ios::sync_with_stdio(0);
    cin>>n;
    int v;
    init();tot=2;
    For(u,1,n){
        cin>>v;
        add(u,v);
    }
    For(i,1,n){
        if(!dfn[i])dfs_clock=0,tarjan(i);
    }
    cout<<ans<<endl;
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值