关于你谷玄学的评测

回复帖子

@HTensor 2020-09-16 12:58 回复

P3371

P4779

对于以下代码片段(即函数dij的返回值没有被承接)

int dij() {
   //something
}
int main() {
   //sth
   dij();
}

在P3371会TLE,而P4779正常通过,P3371下载数据后 洛谷在线IDE也可正常测试

完整代码:

#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 5, M = 1e6 + 6, inf = 2147483647;
struct Edge {
    int to, nxt, val;
} Edge[M << 1];
int head[N], dis[N], cnt, n, m, s;
struct Point {
    int id, dis;
    Point(int _id, int _dis) : id(_id), dis(_dis) {}
    bool operator < (const Point &a) const {
        return dis > a.dis;
    }
};
void addEdge(int u, int v, int w) {
    Edge[++cnt].to = v;
    Edge[cnt].val = w;
    Edge[cnt].nxt = head[u];
    head[u] = cnt;
}
priority_queue<Point> Q;
int dij() {
    fill(dis, dis + N, inf);
    dis[s] = 0; Q.push(Point(s, 0));
    while(!Q.empty()) {
        int u = Q.top().id, d = Q.top().dis; Q.pop();
        if(d != dis[u]) continue;
        for(int i = head[u]; i; i = Edge[i].nxt) {
            int to = Edge[i].to, tod = Edge[i].val;
            if(dis[to] > dis[u] + tod) {
                dis[to] = dis[u] + tod;
                Q.push(Point(to, dis[to]));
            }
        }
    }
}
int main() {
    scanf("%d%d%d", &n, &m, &s);
    for(int i = 1; i <= m; i++) {
        int u, v, w; scanf("%d%d%d", &u, &v, &w);
        addEdge(u, v, w);
    }

    dij();
    for(int i = 1; i <= n; i++) {
        printf("%d ", dis[i]);
    }
printf("\n");
    return 0;
} 
@HTensor 2020-09-16 13:01 回复 举报

PS: 貌似不是ub, stackoverflow 上看到了帖子说会被丢弃

@sjx233_ 2020-09-16 13:17 回复 举报
// 没有返回值会返回随机数
int rand() { }

加个 -Wall 就能查出的错误有必要放到洛谷上吗(

@HTensor 2020-09-16 13:20 回复 举报

@sjx233_

确实是随机数 不信你承接我的 dij() 试试

而且只是探讨为什么本应该被丢弃的返回值会影响到结果。。

@HTensor 2020-09-16 13:26 回复 举报

前来结帖

引用自: stackoverflow

If a function is defined to return a value but does not, and the calling function attempts to use the return value, you invoke undefined behavior.

This is spelled out in section 6.9.1p12 of the [C standard](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf):

If the } that terminates a function is reached, and the value of the function call is used by the caller, the behavior is undefined.

You got "lucky" in this case that the program appeared to work properly, but there's no guarantee of that. Had you compiled with different optimization settings or a different compiler altogether you could end up with different results.

So the moral of the story: if the function says it returns a value, always return a value.
反馈
如果你认为某个帖子有问题,欢迎向洛谷反馈,以帮助更多的同学。



请具体说明理由,以增加反馈的可信度。