Codeforces 825G Tree Queries(DFS)

来源:互联网 发布:朴素贝叶斯算法matlab 编辑:程序博客网 时间:2024/06/05 16:33
/**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;}

原创粉丝点击