社区讨论

各位大佬帮忙看看这个结构体有什么问题呢?

P3379【模板】最近公共祖先(LCA)参与者 2已保存回复 1

讨论操作

快速查看讨论及其快照的属性,并进行相关操作。

当前回复
1 条
当前快照
1 份
快照标识符
@lo7xyngm
此快照首次捕获于
2023/10/27 09:35
2 年前
此快照最后确认于
2023/10/27 09:35
2 年前
查看原帖
一直WA,找了一个晚上,发现把结构体数组换成普通数组就对了,很奇怪,这是为什么呢?呜呜呜呜
CPP
#include <cstdio>
#include <cstring>
using namespace std;
const int N = 5e5;
struct edge{
    int u,v;
}e[(N<<1)+10];
int idx = 1;
int first[N+5];
int next[(N<<1)+10];
int fa[N+5][21];
int depth[N+5];
void add(int x,int y){
    e[idx].u = x;
    e[idx].v = y;
    next[idx] = first[x];
    first[x] = idx++;
}
void dfs(int x,int father){
    depth[x] = depth[father] + 1;
    fa[x][0] = father;
    for(int i=1;i<=20;i++){
        fa[x][i] = fa[fa[x][i-1]][i-1];
    }
    for(int j=first[x];j!=-1;j=next[j]){
        int k = e[j].v;
        if(k==father) continue;
        dfs(k,x);
    }
}
void swap_(int& x,int& y){
    x = x^y;
    y = x^y;
    x = x^y;
}
int main(){
    int n,m,s;
    memset(first,-1,sizeof(first));
    memset(depth,0,sizeof(depth));
    scanf("%d%d%d",&n,&m,&s);
    freopen("test1.out","w",stdout);
    int op1,op2;
    while(--n){
        scanf("%d%d",&op1,&op2);
        add(op1,op2); add(op2,op1);
    }
    dfs(s,0);
    while(m--){
        scanf("%d%d",&op1,&op2);
        if(depth[op1]<depth[op2]) swap_(op1,op2);
        for(int i=20;i>=0;i--){
            if(depth[op1]==depth[op2]) break;
            if(depth[fa[op1][i]]>=depth[op2]) op1 = fa[op1][i];
        }
        if(op1==op2){
            printf("%d\n",op1);
            continue;
        }
        for(int i=20;i>=0;i--){
            if(fa[op1][i]!=fa[op2][i]){
                op1 = fa[op1][i];
                op2 = fa[op2][i];
            }
        }
        printf("%d\n",fa[op1][0]);
    }
    return 0;
}

回复

1 条回复,欢迎继续交流。

正在加载回复...