Bzoj3631【JLOI2014】松鼠的新家

来源:互联网 发布:如何让php文件常驻内存 编辑:程序博客网 时间:2024/04/26 16:42

Solution

先考虑在序列上的做法。注意到是先处理完所有修改后才做询问,那么每次区间加上一个数时就只须在左右端点分别打上一个+和-的标记,最后询问时将整个序列从左到右扫一遍即可。
树上同理。

#include<cstdio>#include<cstring>#include<cstdlib>#include<iostream>using namespace std;const int maxn = 300005;struct edge{    int x,y,next;    edge(){}    edge(int _x,int _y,int _nt): x(_x) , y(_y) , next(_nt){}}e [maxn << 1];int head[maxn] , tot = 0;inline void addedge(int x,int y){    e[++tot] = edge( x , y , head[x] ); head[x] = tot;    e[++tot] = edge( y , x , head[y] ); head[y] = tot;}int top[maxn],p[maxn],siz[maxn],son[maxn],fa[maxn],dep[maxn];int n,m,T;int tag[maxn][2],a[maxn],c[maxn],s[maxn];void DFS1(int x){    siz[x] = 1; son[x] = 0;    for(int y,i = head[x] ; i ; i = e[i].next ){        y = e[i].y;        if( dep[y] ) continue;        dep[y] = dep[x] + 1;        fa[y] = x;        DFS1( y );        siz[x] += siz[y];        if( siz[y] > siz[son[x]] ) son[x] = y;    }}void DFS2(int x,int chain){    p[x] = ++T; top[x] = chain;    if( son[x] ) DFS2( son[x] , chain );    for(int y,i = head[x] ; i ; i = e[i].next ){        y = e[i].y;        if( p[y] || y == son[x] ) continue;        DFS2( y , y );    }}int sum = 0;void DFS3(int x){    sum += tag[x][0];    s[x] = sum;    sum -= tag[x][1];    if( son[x] ) DFS3(son[x]);}int main(){    scanf("%d",&n);    for(int i = 1 ; i <= n ; i++)scanf("%d",&a[i]);    for(int i = 2 ; i <= n ; i++) c[a[i]]++;    for(int x,y,i = 1 ; i <= n-1 ; i++){        scanf("%d%d",&x,&y);        addedge(x,y);    }    dep[1]=1;    DFS1( 1 );    DFS2( 1 , 1 );    for(int x,y,i = 1 ; i <= n-1 ;i++){        x = a[i]; y = a[i+1];        while( top[x] != top[y] ){            if( dep[top[x]] < dep[top[y]] )swap( x, y );                tag[top[x]][0]++;            tag[x][1]++;            x = fa[top[x]];        }        if( dep[x] > dep[y] ) swap( x , y );        tag[x][0]++;        tag[y][1]++;    }    for(int i = 1 ; i <= n ; i++)        if( i == top[i] ) DFS3(i);    for(int i = 1 ; i <= n ; i++)        printf("%d\n",s[i]-c[i]);}
0 0
原创粉丝点击