Codeforces 825G Tree Queries(DFS)

/**
Codeforces 825G Tree Queries

题意:一棵树开始全部节点为白色,有m个操作,操作有两种:
1 x 将x的节点变为黑色(第一个操作一定是1)
2 x 查询x到某个黑色节点的简单路径上的标号最小的节点
操作给出的是操作类型(1和2) 还有z,给出的不是x,x = (z + last) % n + 1
其中last为查询操作的上一次的结果,初始时last = 0

思路:读懂了题意就很简单了,先让第一次变为黑色的节点为根生成有向树,记录此时所有的答案res[i]
当让其他节点(比如u)变为黑色时,其实u的孩子节点的答案不会变化,其他节点的答案也其实只看根节
点到u路径上的最小值是否有贡献,所以对于1操作记录,记录所有1操作的最小值ans, 当查询x时的时候
答案就是min(ans, res[x])
**/
#include<cstdio>
#include<cstring>
#include<queue>
#include<cmath>
#include<iostream>
#include<algorithm>
const int maxn = 1e6 + 10;
const int INF = 1e9;
using namespace std;

int res[maxn], ans, n, m;
vector<int> G[maxn];

void dfs(int x, int fa, int data) {
    res[x] = min(x, data);
    for(int i = 0; i < G[x].size(); i++) {
        int to = G[x][i];
        if(to == fa) continue;
        dfs(to, x, res[x]);
    }
}

int main() {
    while(scanf("%d %d", &n, &m) != EOF) {
        int from, to, op, x;
        for(int i = 1; i <= n; i++) G[i].clear();
        for(int i = 1; i < n; i++) {
            scanf("%d %d", &from, &to);
            G[from].push_back(to);
            G[to].push_back(from);
        }
        scanf("%d %d", &op, &x); x = (x % n) + 1;
        dfs(x, 0, INF); m--; ans = 0;
        int k = x;
        while(m--) {
            scanf("%d %d", &op, &x);
            x = ((x + ans) % n) + 1;
            if(op == 1) k = min(k, res[x]);
            else { ans = min(k, res[x]); printf("%d\n", ans); }
        }
    }
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值