Codeforces Round #787 (Div. 3) F. Vlad and Unfinished Business

F. Vlad and Unfinished Business

Link

题意: 给你一棵树,里面遍布几个任务点一个目的地,求从出发点开始最短通过所有任务点最终到达目的地的最小步数。

思路: 记录从 x x x开始到达目的地 y y y的深度,并且把 y y y点也当个任务点,统计所有任务点沿径距离到出发点 x x x的距离和。最终再特殊处理 y y y,因为不用回到 x x x点,所以我们减去 y y y的深度即可,使用DFS实现。

代码:

#include<bits/stdc++.h>
using namespace std;
#define int long long
set<int>s;
const int N = 2e5+10;
int idx,e[N<<1],h[N],ne[N<<1];
int f[N];
bool st[N];
int dep[N];
void add(int a,int b){
    e[idx]=b;
    ne[idx]=h[a];
    h[a]=idx++;
}
void dfs(int u,int fa,int deep){
    dep[u]=deep;
    for(int i=h[u];i!=-1;i=ne[i]){
        int j=e[i];
        if(j==fa)continue;
        f[j]=u;
        dfs(j,u,deep+1);
    }
}
void cf(){
    int n,k;
    cin>>n>>k;
    int x,y;
    cin>>x>>y;
    s.clear();
    idx=0;
    for(int i=1;i<=n;i++){
        dep[i]=0;
        st[i]=false;
        h[i]=-1;
    }
    for(int i=1;i<=k;i++){
        int xx;
        cin>>xx;
        s.insert(xx);
    }
    for(int i=1;i<=n-1;i++){
        int a,b;
        cin>>a>>b;
        add(a,b);
        add(b,a);
    }
    for(int i=1;i<=n;i++)st[i]=false;
    st[x]=true;
    dfs(x,x,0);
    s.insert(y);
    int res=0;
    for(auto g:s){
        int gg=g;
        while(!st[gg]){
            st[gg]=true;
            res+=2;
            gg=f[gg];
        }
    }
    cout<<res-dep[y]<<endl;
} 
signed main(){
    // freopen("input.txt","r",stdin);
	// freopen("output.txt","w",stdout);
    int t=1;
    cin>>t;
    while(t--){
        cf();
    }
}
  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值