其他分享
首页 > 其他分享> > P3258 [JLOI2014]松鼠的新家 (简单的点差分)

P3258 [JLOI2014]松鼠的新家 (简单的点差分)

作者:互联网

https://www.luogu.org/problemnew/show/P3258

注意开始和最后结尾

  1 #include <bits/stdc++.h>
  2 #define read read()
  3 #define up(i,l,r) for(register int i = (l);i <= (r);i++)
  4 #define down(i,l,r) for(register int i = (l);i >= (r);i--)
  5 #define traversal_vedge(i) for(register int i = head[u]; i ;i = e[i].nxt)
  6 #define ll long long
  7 using namespace std;
  8 int read
  9 {
 10     int x = 0, f = 1; char ch = getchar();
 11     while(ch < 48 || ch > 57) {if(ch == '-')f = -1; ch = getchar();}
 12     while(ch >=48 && ch <=57) {x = 10 * x + ch - 48;ch = getchar();}
 13     return x * f; 
 14 }
 15 //--------------------------------------------------------------------
 16 const int N = 300005;
 17 int n,a[N];
 18 struct edge{
 19     int v,nxt;
 20 }e[N<<1]; int tot,head[N];
 21 void add(int u,int v) {e[++tot] = (edge){v,head[u]};head[u] = tot;}
 22 
 23 int dep[N],size[N],fa[N],top[N];
 24 int cnt[N];
 25 
 26 void dfs(int u)
 27 {
 28     dep[u] = dep[fa[u]]+1;
 29     size[u] = 1;
 30     top[u] = u;
 31     int hson_id = 0,hson_size = 0;
 32     traversal_vedge(i)
 33     {
 34         int v = e[i].v;
 35         if(v == fa[u]) continue;
 36         fa[v] = u;
 37         dfs(v);
 38         size[u] += size[v];
 39         if(size[v] > hson_size) hson_id = v,hson_size = size[v];
 40     }
 41     if(hson_id) top[hson_id] = u;
 42 }
 43 
 44 int find(int u)
 45 {
 46     if(top[u] == u) return u;
 47     top[u] = find(top[u]);
 48     return top[u];
 49 }
 50 
 51 int lca(int x,int y)
 52 {
 53     if(find(x) != find(y))
 54     {
 55         if(dep[top[x]] > dep[top[y]]) return lca(fa[top[x]],y);
 56         else return lca(x,fa[top[y]]);
 57     }
 58     return dep[x] > dep[y] ? y : x;
 59 }
 60 
 61 void dfs_tree(int u)
 62 {
 63     traversal_vedge(i)
 64     {
 65         int v = e[i].v;
 66         if(v == fa[u]) continue;
 67         dfs_tree(v);
 68         cnt[u] += cnt[v];
 69     }
 70 }
 71 
 72 void readdata()
 73 {
 74     n = read;
 75     up(i,1,n) a[i] = read;
 76     up(i,1,n-1)
 77     {
 78         int u = read, v = read;
 79         add(u,v);
 80         add(v,u);
 81     }
 82     dfs(1);
 83     up(i,1,n-1)
 84     {
 85         int u = a[i], v = a[i+1];
 86         //cnt[u]++; 
 87         cnt[fa[u]]++;
 88         cnt[v]++;
 89         int LCA = lca(u,v);
 90         cnt[LCA]--; cnt[fa[LCA]]--;
 91     }
 92     dfs_tree(1);
 93     up(i,1,n) 
 94     {
 95         if(i == a[1]) cnt[i]++;
 96         else if(i == a[n]) cnt[i]--;
 97         printf("%d\n",cnt[i]);
 98     }
 99 }
100 
101 int main()
102 {
103     readdata();
104     return 0;
105 }

 

标签:cnt,JLOI2014,return,int,top,差分,P3258,ch,read
来源: https://www.cnblogs.com/mzg1805/p/10416942.html