用int代替void声明函数报错
  • 板块学术版
  • 楼主John_steve
  • 当前回复9
  • 已保存回复9
  • 发布时间2022/12/16 17:23
  • 上次更新2023/10/24 07:32:11
查看原帖
用int代替void声明函数报错
533537
John_steve楼主2022/12/16 17:23

省流: 用int 声明函数与用 void 有什么区别 ?


具体经过:

LCA模板题

我在重刷时自信地使用链式前向星存图

然后爆零

代码如下

#include <cstdio>
#include <algorithm>
using namespace std;
const int N = 500010;

inline int read()
{
    int x=0, f=1; char c;
    while ((c=getchar())<'0' || c>'9')
        if (c=='-') f = -1;
    while (c>='0' && c<='9')
        x=(x<<3)+(x<<1)+(c^48), c=getchar();
    return x * f;
}

struct edge
{
    int to, next;
} edges[N * 2];

int head[N], cnt;

// 重点在这里
// 改为inline void add 就能AC
inline int add(int from, int to)
{
    edges[++cnt].to = to;
    edges[cnt].next = head[from];
    head[from] = cnt;
}

int n, m, s;
int fa[N][20], dep[N], Log2[N];

void prelca(int x, int fath=0)
{
    dep[x] = dep[fath] + 1;
    fa[x][0] = fath;
    for (int i=1; i<=Log2[dep[x]]; i++)
        fa[x][i] = fa[fa[x][i-1]][i-1];
    for (int e=head[x]; e!=0; e=edges[e].next)
        if (edges[e].to != fath)
            prelca(edges[e].to, x);
}

int lca(int a, int b)
{
    if (dep[a] > dep[b])
        swap(a, b);
    while (dep[a] != dep[b])
        b = fa[b][Log2[dep[b]-dep[a]]];
    if (a == b)
        return a;
    for (int i=Log2[dep[a]]; i>=0; i--)
        if (fa[a][i] != fa[b][i])
            a=fa[a][i], b=fa[b][i];
    return fa[a][0];
}

int main()
{
    n=read(); m=read(); s=read();
    for (int i=2; i<=n; i++)
        Log2[i] = Log2[i/2] + 1;
    int a, b;
    for (int i=1; i<n; i++)
    {
        a=read(); b=read();
        add(a, b);
        add(b, a);
    }
    prelca(s);
    while (m--)
    {
        a=read(); b=read();
        printf("%d\n", lca(a, b));
    }
    return 0;
}

经过漫长的找bug 发现是写了 int add

改成 void add 就能通过

但理论上 用int不也没问题吗?

2022/12/16 17:23
加载中...