为什么传参不能直接传快读啊

P4779 【模板】单源最短路径(标准版)

GI录像机 @ 2022-04-19 15:09:49

这是代码:

#include<bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
int read() {
    int f = 1, x = 0;
    char c = getchar();
    while (c < '0' || c > '9') {
        if (c == '-')f = -1;
        c = getchar();
    }
    while (c >= '0' && c <= '9') {
        x = x * 10 + c - '0';
        c = getchar();
    }
    return f * x;
}
void write(long long x) {
    if (x < 0) {
        putchar('-');
        x = -x;
    }
    if (x > 9)write(x / 10);
    putchar(x % 10 + '0');
}
int n = read(), m = read(), s = read(), l, tot, head[N];
long long dis[N];
struct Node {
    int to, nxt, w;
} a[N << 1];
struct node {
    int pos;
    long long w;
    bool operator <(const node& c)const {
        return c.w < w;
    }
};
void add(int u, int v, int w) {
    a[++tot].to = v;
    a[tot].w = w;
    a[tot].nxt = head[u];
    head[u] = tot;
}
void dijkstra() {
    dis[s] = 0;
    priority_queue<node>q;
    q.push({
        s, 0
    });
    while (!q.empty()) {
        node now = q.top();
        q.pop();
        int u = now.pos;
        if (now.w != dis[u])continue;
        for (int i = head[u]; i; i = a[i].nxt) {
            int v = a[i].to, w = a[i].w;
            if (dis[v] > dis[u] + w) {
                dis[v] = dis[u] + w;
                q.push({
                    v, dis[v]
                });
            }
        }
    }
}
int main() {
    for (int i = 1; i <= m; i++) {
        //int u = read(), v = read(), w = read();
        add(read(), read(), read());
    }
    memset(dis, 0x3f3f3f3f, sizeof(dis));
    dijkstra();
    for (int i = 1; i <= n; i++) {
        write(dis[i]);
        putchar(' ');
    }
    return 0;
}

在建图时我直接传快读的值连样例都过不了,改掉就 A 了。为什么不能这么用快读啊。


by rzh123 @ 2022-04-19 15:11:35

UB,编译器不知道应该先执行哪个参数的快读,就自由发挥了


by Usada_Pekora @ 2022-04-19 15:20:19

这样写貌似是倒着传参的,看编译器


by LYqwq @ 2022-04-19 15:23:15

函数传参顺序是倒着传的


by rzh123 @ 2022-04-19 15:23:23

一般编译器的实现是倒着传,有一小部分是正的,实际上是 UB


by GI录像机 @ 2022-04-19 15:40:39

阿哲,谢谢各位 Dalao


|