UVALIVE 3486 Cells

通过入栈出栈顺序判断祖先关系

这里UVALIVE还

#include <map>
#include <set>
#include <list>
#include <cmath>
#include <ctime>
#include <deque>
#include <stack>
#include <queue>
#include <cctype>
#include <cstdio>
#include <string>
#include <vector>
#include <climits>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
#define LL long long
#define PI 3.1415926535897932626
using namespace std;
int gcd(int a, int b) {return a % b == 0 ? b : gcd(b, a % b);}
#define MAXN 20000010
int pre[MAXN],post[MAXN];
int start[300005],c[300005];
int N;
void dfs(int root)
{
        stack<int>s;
        s.push(root);
        pre[root] = 0;
        int dfs_clock = 0;
        while (!s.empty())
        {
                int x = s.top();
                if (pre[x])
                {
                        post[x] = ++dfs_clock;
                        s.pop();
                        continue;
                }
                pre[x] = ++dfs_clock;
                for (int i =start[x]; i < start[x] + c[x] ; i++)
                {
                        if (i < N)
                        {
                                pre[i] = 0 ;
                                s.push(i);
                        }
                        else
                        {
                                pre[i] = ++dfs_clock;
                                post[i] = ++dfs_clock;
                        }
                }
        }
}
int main()
{
        int T ,kase = 1;
        scanf("%d",&T);
        while (T--)
        {
                printf("Case %d:
",kase++);
                scanf("%d",&N);
                start[0] = 1;
                for (int i = 0; i < N; i++)
                {
                        scanf("%d",&c[i]);
                        if (i)
                                start[i] = start[i - 1] + c[i - 1];
                }
                dfs(0);
                int m;
                scanf("%d",&m);
                while (m--)
                {
                        int u,v;
                        scanf("%d%d",&u,&v);
                        if(pre[u] < pre[v] && post[u] > post[v]) puts("Yes");
                        else puts("No");
                }
                if (T) putchar('
');
        }
}

是不行,ZOJ过了。

原文地址:https://www.cnblogs.com/Commence/p/4048012.html