【CF131D】Subway

题目大意:给定一棵 N 个节点的基环树,求各个点到环的最小距离。

题解:除了找环的必须参数之外,对每个点维护一个 fa 即可。

代码如下

#include <bits/stdc++.h>
#define fi first
#define se second
#define pb push_back
#define mp make_pair
#define all(x) x.begin(),x.end()
using namespace std;
typedef long long ll;
typedef pair<int,int> P;
const int mod=1e9+7;
const int inf=0x3f3f3f3f;
const int maxn=3010;
inline ll gcd(ll a,ll b){return b?gcd(b,a%b):a;}
inline ll sqr(ll x){return x*x;}
inline ll read(){
    ll x=0,f=1;char ch;
    do{ch=getchar();if(ch=='-')f=-1;}while(!isdigit(ch));
    do{x=x*10+ch-'0';ch=getchar();}while(isdigit(ch));
    return f*x;
}

vector<P> G[maxn];int tot=1;
vector<int> cyc;
int n,fa[maxn],vis[maxn],dep[maxn];
bool has[maxn];

void read_and_parse(){
    n=read();
    for(int i=1;i<=n;i++){
        int x=read(),y=read();
        G[x].pb(mp(y,++tot)),G[y].pb(mp(x,++tot));
    }
}

void dfs(int u,int fe){
    vis[u]=1;
    for(int i=0;i<G[u].size();i++){
        int v=G[u][i].fi,e=G[u][i].se;
        if(fe==(e^1))continue;
        if(!vis[v])fa[v]=u,dfs(v,e);
        else if(vis[v]==1){
            for(int x=u;x!=v;x=fa[x])cyc.pb(x),has[x]=1;
            cyc.pb(v),has[v]=1;
        }
    }
    vis[u]=2;
}
void get(int u){
    has[u]=1;
    for(int i=0;i<G[u].size();i++){
        int v=G[u][i].fi;if(has[v])continue;
        dep[v]=dep[u]+1,get(v);
    }
}

void solve(){
    dfs(1,0);
    for(int i=0;i<cyc.size();i++)get(cyc[i]);
    for(int i=1;i<=n;i++)printf("%d ",dep[i]);
    puts("");
}

int main(){
    read_and_parse();
    solve();
    return 0;
}

转载于:https://www.cnblogs.com/wzj-xhjbk/p/10621217.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值