BZOJ 1103 大都市(dfs序+树状数组)
应该是一道很水的题吧。。。
显然可以用树链剖分解决这个问题,虽然不知道多一个log会不会T。但是由于问题的特殊性。
每次修改都是将边权为1的边修改为0,且询问的是点i到根节点的路径长度。
令点i到根节点的路径长度为w[i],显然初始时w[i]=dep[i].考虑修改边为(u,v),那么令u为深度大的点。
那么u的子树的所有答案就要减1.考虑dfs序,则每次需要修改的是一段连续的区间。
树状数组维护单点查询,区间修改,美滋滋。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
# include <cstdio> # include <cstring> # include <cstdlib> # include <iostream> # include <vector> # include <queue> # include <stack> # include <map> # include <set> # include <cmath> # include <algorithm> using namespace std; # define lowbit(x) ((x)&(-x)) # define pi acos(-1.0) # define eps 1e-9 # define MOD 1000000000 # define INF 1000000000 # define mem(a,b) memset(a,b,sizeof(a)) # define FOR(i,a,n) for(int i=a; i<=n; ++i) # define FO(i,a,n) for(int i=a; i<n; ++i) # define bug puts("H"); # define lch p<<1,l,mid # define rch p<<1|1,mid+1,r # define mp make_pair # define pb push_back typedef pair<int,int> PII; typedef vector<int> VI; # pragma comment(linker, "/STACK:1024000000,1024000000") typedef long long LL; int Scan() { int x=0,f=1;char ch=getchar(); while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();} while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();} return x*f; } void Out(int a) { if(a<0) {putchar('-'); a=-a;} if(a>=10) Out(a/10); putchar(a%10+'0'); } const int N=250005; //Code begin... struct Edge{int p, next;}edge[N<<1]; int tree[N], head[N], cnt=1, DFN[N][2], dep[N], pos, n; void add_edge(int u, int v){edge[cnt].p=v; edge[cnt].next=head[u]; head[u]=cnt++;} void dfs(int x, int fa){ DFN[x][0]=++pos; for (int i=head[x]; i; i=edge[i].next) { int v=edge[i].p; if (v==fa) continue; dep[v]=dep[x]+1; dfs(v,x); } DFN[x][1]=pos; } int query(int x){ int res=0; while (x) res+=tree[x], x-=lowbit(x); return res; } void add(int x, int val){while (x<=n+1) tree[x]+=val, x+=lowbit(x);} int main () { int m, u, v; char s[5]; scanf("%d",&n); FO(i,1,n) scanf("%d%d",&u,&v), add_edge(u,v), add_edge(v,u); dfs(1,0); FOR(i,1,n) add(DFN[i][0],dep[i]), add(DFN[i][0]+1,-dep[i]); scanf("%d",&m); m+=n-1; while (m--) { scanf("%s%d",s,&u); if (s[0]=='W') printf("%d\n",query(DFN[u][0])); else { scanf("%d",&v); if (dep[u]<dep[v]) swap(u,v); add(DFN[u][0],-1); add(DFN[u][1]+1,1); } } return 0; }