树上差分
这应该是一道很简单的树上差分了。。就是问每个点被覆盖了多少次。
要注意我们最后dfs后,要把除第一个节点以外的所有点的-1,因为有些点作为起点和终点覆盖了两次,按照题目意思是不用覆盖两次的。
#include <bits/stdc++.h>
#define INF 0x3f3f3f3f
#define full(a, b) memset(a, b, sizeof a)
using namespace std;
typedef long long ll;
inline int lowbit(int x){ return x & (-x); }
inline int read(){
int X = 0, w = 0; char ch = 0;
while(!isdigit(ch)) { w |= ch == '-'; ch = getchar(); }
while(isdigit(ch)) X = (X << 3) + (X << 1) + (ch ^ 48), ch = getchar();
return w ? -X : X;
}
inline int gcd(int a, int b){ return a % b ? gcd(b, a % b) : b; }
inline int lcm(int a, int b){ return a / gcd(a, b) * b; }
template<typename T>
inline T max(T x, T y, T z){ return max(max(x, y), z); }
template<typename T>
inline T min(T x, T y, T z){ return min(min(x, y), z); }
template<typename A, typename B, typename C>
inline A fpow(A x, B p, C lyd){
A ans = 1;
for(; p; p >>= 1, x = 1LL * x * x % lyd)if(p & 1)ans = 1LL * x * ans % lyd;
return ans;
}
const int N = 300005;
int n, s[N], cnt, head[N], depth[N], p[N][20], t, val[N];
bool vis[N];
struct Edge { int v, next; }edge[N<<1];
void addEdge(int a, int b){
edge[cnt].v = b, edge[cnt].next = head[a], head[a] = cnt ++;
}
void dfs(int s, int fa){
depth[s] = depth[fa] + 1;
p[s][0] = fa;
for(int i = 1; i <= t; i ++){
p[s][i] = p[p[s][i - 1]][i - 1];
}
for(int i = head[s]; i != -1; i = edge[i].next){
int u = edge[i].v;
if(u == fa) continue;
dfs(u, s);
}
}
int lca(int x, int y){
if(depth[x] < depth[y]) swap(x, y);
for(int i = t; i >= 0; i --){
if(depth[p[x][i]] >= depth[y]) x = p[x][i];
}
if(x == y) return y;
for(int i = t; i >= 0; i --){
if(p[x][i] != p[y][i]) x = p[x][i], y = p[y][i];
}
return p[y][0];
}
void dfs(int s){
vis[s] = true;
for(int i = head[s]; i != -1; i = edge[i].next){
int u = edge[i].v;
if(vis[u]) continue;
dfs(u);
val[s] += val[u];
}
}
int main(){
full(head, -1);
n = read();
for(int i = 0; i < n; i ++) s[i] = read();
for(int i = 0; i < n - 1; i ++){
int u = read(), v = read();
addEdge(u, v), addEdge(v, u);
}
t = (int)(log(n) / log(2)) + 1;
dfs(s[0], 0);
for(int i = 0; i < n - 1; i ++){
val[s[i]] ++, val[s[i + 1]] ++;
int f = lca(s[i], s[i + 1]);
val[f] --, val[p[f][0]] --;
}
dfs(s[0]);
for(int i = 1; i < n; i ++) val[s[i]] --;
for(int i = 1; i <= n; i ++) printf("%d
", val[i]);
return 0;
}