给一棵树,每次每次询问一个点是否是另一个点的祖先?

首先,题目的读入就有点坑爹,注意,每个节点的值是说明它下面有多少个儿子节点,直接对于每个下标保存一个值即可。

对于查询是否是祖先,我们可以对于每一个节点打上两个dfs标记,如果一个点是另一个点的祖先,那么它的两个标记一定在祖先的范围之内。

还要注意,由于点数极其多,直接dfs会爆栈,那么我们需要手动模拟栈的执行过程。简单,数组模拟就好了。

召唤代码君:

#include <iostream>
#include <cstring>
#include <cstdio>
#include <vector>
#define maxn 20022000
using namespace std; int l[maxn],r[maxn],sum[];
bool a[maxn];
int T,n,k,m,cur,TAG=,dfs_clock,cas=;
int stack[maxn],top; void dfs()
{
for (int i=; i<maxn; i++) a[i]=false;
dfs_clock=stack[top=]=;
while (top>){
k=stack[top];
if (!a[k]){
a[k]=true,l[k]=++dfs_clock;
if (k<n)
for (int i=k==?:sum[k-]+; i<=sum[k]; i++) stack[++top]=i;
}
else r[k]=++dfs_clock,top--;
}
} int main()
{
int x,y;
scanf("%d",&T);
while (T--){
scanf("%d",&n);
for (int i=; i<n; i++){
scanf("%d",&k);
sum[i]=i==?k:sum[i-]+k;
}
dfs();
if (cas++) printf("\n");
printf("Case %d:\n",cas);
scanf("%d",&m);
while (m--){
scanf("%d%d",&x,&y);
if (l[x]<l[y] && r[x]>r[y]) puts("Yes");
else puts("No");
}
}
return ;
}

UVAlive3486_Cells的更多相关文章

随机推荐

  1. (转)JPEG图片数据结构分析- 附Png数据格式详解.doc

       一.简述 JPEG是一个压缩标准,又可分为标准JPEG.渐进式JPEG及JPEG2000三种: ①标准JPEG:以24位颜色存储单个光栅图像,是与平台无关的格式,支持最高级别的压缩,不过,这种压 ...

  2. 解决:新版火狐浏览器3d打不开

    重启:按 Ctrl + Shift + L 键唤出 3d 视图 参考文档:http://tieba.baidu.com/p/4606488108

  3. 3.Sqrt(x)

    要求:Implement int sqrt(int x).  Compute and return the square root of x. 解决方法: 1.牛顿法(Newton's method) ...

  4. 7. Reverse Words in a String

    题目: Given an input string, reverse the string word by word. For example,Given s = "the sky is b ...

  5. 安卓:assets目录下的文本文件(不受R文件节制)

    try { InputStream in = getAssets().open("testAsset.txt"); byte[] buffer = new byte[1024]; ...

  6. openldap主机访问控制(基于hostname)

    http://mayiwei.com/2013/03/21/centos6-openldap/ http://www.zytrax.com/books/ldap/ch11/dynamic.html h ...

  7. 生成API文档的软件

    SandCastle:http://shfb.codeplex.com/SourceControl/latest#1952439 HTML Help:http://msdn.microsoft.com ...

  8. mongodb固定集合,建立管理员安全验证

    建立普通集合 db.createCollections aaa; 建立固定集合名称book capped true 固定集合 size大小 max:文档数量 db.createCollection(& ...

  9. 自己练习读取写入txt

    读取文件中的内容生成一个list,然后修改list后再写会该文件文件中的格式是:AA,BB,CC,DDblist = []for line in open('a.txt'): blist.extend ...

  10. java笔记1

    第五天学习笔记 1.面对对象的理解并举例? 面对对象的核心:找合适的对象做合适的事情. 面对对象编程的思想:尽可能的用计算机语言来描述现实生活中的事物. 面对对象:侧重于对象 2.类与对象之间的关系? ...