Timus 1329. Galactic History

原题:1329

题意:给出一棵n个节点的树,问m对节点的从属关系

解法:因为n较大,若对于每一个子问题都进行一次搜索并定会超时。其实只要进行一次dfs,记录每一个节点出现的初始时间和结束时间,这样就可以保证每一个节点出现的时间必定比其下方的节点出现时间早,结束时间晚。~~(这种方法亦可以求最近公共祖先)

代码实现我应用的是模拟指针…

#include <iostream>
using namespace std;

int a[100000], next[100000], n, last[50000] = {0}, tot = 0, sum = 0;
int f[50100][3] = {0};

void insert(int x, int y) {
    a[tot] = y;
    next[tot] = last[x];
    last[x] = tot;
    tot++;
}

void dfs(int t) {
    sum++;
    if (f[t][1] == 0) f[t][1] = sum;
    f[t][2] = sum;
    int k = last[t];
    while (k != 0) {
        if (f[a[k]][1] != 0) {
            k = next[k];
            continue;
        }
        dfs(a[k]);
        sum++;
        f[t][2] = sum;
        k = next[k];
    }
}

int main() {

    cin >> n;
    int s;
    for (int i = 1; i <= n; i++) {
        int x, y;
        cin >> x >> y;
        if (x == -1) s = y;
        else if (y == -1) s = x;
        else {
            insert(x, y);
            insert(y, x);
        }
    }
    dfs(s);
    int m;
    cin >> m;
    for (int i = 1; i <= m; i++) {
        int x, y;
        cin >> x >> y;
        if (f[x][1] < f[y][1] && f[x][2] > f[y][2]) cout << 1 << endl;
        else if (f[y][1] < f[x][1] && f[y][2] > f[x][2]) cout << 2 << endl;
        else cout << 0 << endl;
    }


}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值