CCPC网络赛—Jumping Monkey

这篇博客介绍了CCPC网络赛中的JumpingMonkey问题的解决思路,通过构建树形结构并按所有权值排序,利用深度优先搜索(DFS)确定节点的可达范围,以节点深度作为答案输出。难点在于如何将深度作为关键指标。代码实现包括图的构建、并查集操作和DFS遍历。
摘要由CSDN通过智能技术生成

CCPC网络赛—Jumping Monkey

思路:先把所有的边存下来,不连,然后按所有权值从小到大排序,重新构建一颗树。从小到大枚举所有节点,遍历当前节点的所有连边,若对面节点比当前节点大,则到不了对面,continue,若比当前节点小,则证明当前节点可以到达对面节点的连通块中所有的点,将对面连通块中权值最大的节点与自己连边,这样对面连通块所有节点深度+1,我们将深度作为答案即可输出。
难点:如何想到把深度作为答案输出

#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
#include <math.h>
#include <map>
#include <set>
#include <queue>

using namespace std;
#define endl '\n'
const int maxn = 1e5+5;
const int maxm = maxn << 1;
int head[maxn],nex[maxm],v[maxm],w[maxm],cnt,dis[maxn],vis[maxn],fa[maxn],dep[maxn];
int n,idx,val[maxn];
void add(int x,int y){
    nex[++cnt] = head[x];
    head[x] = cnt;
    v[cnt] = y;
}
int find(int x){
    return fa[x] == x ? x : (fa[x] = find(fa[x]));
}
struct node{
    int val,id;
    friend bool operator < (const node a,const node b){
        return a.val < b.val;
    }
}a[maxn];
vector<int> to[maxn];
void init(){
    idx = cnt = 0;
    for (int i = 1; i <= n; ++i) {
        fa[i] = i;
        head[i] = 0;
        to[i].clear();
    }
}
void bfs(int node){
    memset(dep,0x3f,sizeof dep);
    dep[node] = 1;
    queue<int> q;
    q.push(node);
    while (!q.empty()){
        int now = q.front();q.pop();
        for (int i = head[now]; i; i = nex[i]) {
            int to = v[i];
            if (dep[to] > dep[now] + 1){
                dep[to] = dep[now] + 1;
                q.push(to);
            }
        }
    }
}
void solve(){
    cin >> n;
    init();
    for (int i = 1; i <= n - 1; ++i) {
        int x,y;
        cin >> x >> y;
        to[x].push_back(y);
        to[y].push_back(x);
    }
    for (int i = 1; i <= n; ++i) {
        cin >> a[i].val;
        val[i] = a[i].val;
        a[i].id = i;
    }
    sort(a + 1,a + 1 + n);
    for (int i = 1; i <= n; ++i) {
        int node = a[i].id;
        for(auto k : to[node]){
            if (val[k] > val[node]) continue;
            int fx = find(k);
            fa[fx] = node;
            add(fx,node);
            add(node,fx);
        }
    }
    bfs(a[n].id);
    for (int i = 1; i <= n; ++i) {
        cout << dep[i] << endl;
    }
}
int main(){
    std::ios::sync_with_stdio(false);
    cin.tie(0); cout.tie(0);
    int t;
    cin >> t;
    while (t--) solve();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值