为什么会错
查看原帖
为什么会错
181845
luozhichen楼主2022/1/24 12:01
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int MX = 300007;
int n,k,ans,m;
struct GRAPH {
    int fst[MX],nxt[MX],v[MX],lnum;
    void add(int nu,int nv) {
        nxt[++lnum] = fst[nu];
        fst[nu] = lnum;
        v[lnum] = nv;
    }
} G;
inline void swap(int &a,int &b) {
    a = a ^ b;
    b = a ^ b;
    a = a ^ b;
}
inline int max(int a,int b) {
    return a > b ? a : b;
}
struct CHAIN {
    int root;//所在根节点
    int siz[MX];//子树大小
    int dep[MX];//当前深度
    int fa[MX];//树上的父亲
    int top[MX];//所在重链的顶部
    int son[MX];//重儿子
    int yl[MX];
    inline void dfs1(int x,int f,int d) {
        dep[x] = d;
        siz[x] = 1;
        fa[x] = f;
        for(register int i = G.fst[x]; i; i = G.nxt[i]) {
            int y = G.v[i];
            if(y == f) continue;
            dfs1(y,x,d+1);
            siz[x] += siz[y];
            if(siz[son[x]] < siz[y]) {
                son[x] = y;
            }
        }
    }
    inline void dfs2(int x,int f,int t) {
        top[x] = t;
        if(son[x]) dfs2(son[x],x,t);
        for(register int i = G.fst[x]; i; i=G.nxt[i]) {
            int y = G.v[i];
            if(y == f || y == son[x]) continue;
            dfs2(y,x,y);
        }
    }
    inline int lca(register int x,register int y) {
        while(top[x] != top[y]) {
            if(dep[top[x]] < dep[top[y]]) swap(x,y);
            x = fa[top[x]];
        }
        if(dep[x] > dep[y]) return y;
        else return x;
    }
    inline void dfs3(int s,int fath) {
        for(register int i = G.fst[s]; i; i = G.nxt[i]) {
            int y = G.v[i];
            if(y == fath) {
                continue;
            }
            dfs3(y,s);
            yl[s] += yl[y];
        }
        ans = max(ans,yl[s]);
    }
} C;
int read() {
  int x = 0, w = 1;
  char ch = 0;
  while (ch < '0' || ch > '9') {  // ch 不是数字时
    if (ch == '-') w = -1;        // 判断是否为负
    ch = getchar();               // 继续读入
  }
  while (ch >= '0' && ch <= '9') {  // ch 是数字时
    x = x * 10 + (ch - '0');
    ch = getchar();  // 继续读入
  }
  return x * w;  // 数字 * 正负号 = 实际数值
}
inline void write(int x) {
    if(x<0)
    {
        putchar('-');
        x=-x;
    }
    if(x>9)write(x/10);
    putchar(x%10+'0');
}
int aa[MX];
signed main() {
    cin >> n;
    register int x,y;
    for(register int i = 1;i <= n;++i) cin >> aa[i];
    
    
    for(register int i = 1; i < n; ++i) {
        cin >> x >> y;
        G.add(x,y);
        G.add(y,x);
    }
    C.dfs1(1,0,1);
    C.dfs2(1,0,1);
    //cout <<"Asd";
    for(register int i=1; i<n; ++i) {
        register int x,y;
        x = aa[i],y = aa[i+1];
        ++C.yl[x];
        ++C.yl[y];
        register int xx = C.lca(x,y);
        --C.yl[xx];
        --C.yl[C.fa[xx]];
    }
    C.dfs3(1,0);
    for(int i = 1;i <= n;i++){
    	if(i != aa[1]){
    		C.yl[i]--;
		}
		write(C.yl[i]);
		putchar('\n');
	}
    return 0;
}

#3,#4 第一行多一个1,怎么解决

2022/1/24 12:01
加载中...