hdu 3974 Assign the task 线段树 DFS序

给你一棵树,每次修改一个子树的所有值,然后单点查询。

按照DFS序把节点排列(即在DFS中出现的先后次序),同一个子树在序列中连续。

  1 #include <cstdio>
  2 using namespace std;
  3 typedef long long ll;
  4 int n,q,T,Tc,cnt,sum;
  5 int col[210000],lzy[210000],sta[51000],fin[51000];
  6 int nxt[51000],to[51000],head[51000],ind[51000];
  7 void build(int k,int l,int r)
  8 {
  9     lzy[k] = -1;
 10     if (l == r)
 11     {
 12         col[k] = -1;
 13         return;
 14     }
 15     int mid = l + r >> 1;
 16     build(k << 1,l,mid);
 17     build(k << 1 | 1,mid + 1,r);
 18 }
 19 void down(int k,int l,int r)
 20 {
 21     if (l == r)
 22     {
 23         lzy[k] = -1;
 24         return;
 25     }
 26     int mid = l + r >> 1;
 27     col[k << 1] = lzy[k];
 28     col[k << 1 | 1] = lzy[k];
 29     lzy[k << 1] = lzy[k];
 30     lzy[k << 1 | 1] = lzy[k];
 31     lzy[k] = -1;
 32 }
 33 void change(int k,int l,int r,int x,int y,int c)
 34 {
 35     if (x <= l && r <= y)
 36     {
 37         lzy[k] = c;
 38         col[k] = c;
 39         return;
 40     }
 41     if (lzy[k] != -1) down(k,l,r);
 42     int mid = l + r >> 1;
 43     if (x <= mid) change(k << 1,l,mid,x,y,c);
 44     if (y >= mid + 1) change(k << 1 | 1,mid + 1,r,x,y,c);
 45 }
 46 int query(int k,int l,int r,int x)
 47 {
 48     if (l == r) return col[k];
 49     if (lzy[k] != -1) down(k,l,r);
 50     int mid = l + r >> 1;
 51     if (x <= mid) return query(k << 1,l,mid,x);
 52     if (x >= mid + 1) return query(k << 1 | 1,mid + 1,r,x);
 53 }
 54 void add(int x,int y)
 55 {
 56     nxt[++cnt] = head[x];
 57     to[cnt] = y;
 58     head[x] = cnt;
 59 }
 60 void dfs(int x)
 61 {
 62     sta[x] = ++sum;
 63     for (int i = head[x];i;i = nxt[i])
 64         dfs(to[i]);
 65     fin[x] = sum;
 66 }
 67 int main()
 68 {
 69     for (scanf("%d",&T);T;T--)
 70     {
 71         printf("Case #%d:\n",++Tc);
 72         scanf("%d",&n);
 73         int tx,ty;
 74         for (int i = 1;i <= n - 1;i++)
 75         {
 76             scanf("%d%d",&tx,&ty);
 77             add(ty,tx);
 78             ind[tx]++;
 79         }
 80         for (int i = 1;i <= n;i++)
 81             if (ind[i] == 0)
 82             {
 83                 dfs(i);
 84                 break;
 85             }
 86         build(1,1,n);
 87         scanf("%d",&q);
 88         char str[10];
 89         for (int i = 1;i <= q;i++)
 90         {
 91             scanf("%s",str);
 92             if (str[0] == 'T')
 93             {
 94                 scanf("%d%d",&tx,&ty);
 95                 change(1,1,n,sta[tx],fin[tx],ty);
 96             }else
 97             {
 98                 scanf("%d",&tx);
 99                 printf("%d\n",query(1,1,n,sta[tx]));
100             }
101         }
102         for (int i = 1;i <= n;i++)
103             ind[i] = head[i] = 0;
104         for (int i = 1;i <= cnt;i++)    
105             nxt[i] = 0;
106         cnt = sum = 0; 
107     }
108     return 0;
109 }
posted @ 2020-01-13 22:20  IAT14  阅读(98)  评论(0编辑  收藏  举报