为什么按c提交只有一半分,按c++提交却可以ac?

P1314 [NOIP2011 提高组] 聪明的质监员

xyjstud @ 2024-03-12 23:12:27

我是按c程序写的,但是死活ac不了,后面随手换成c++就直接通过了?

#include <stdio.h>
#include <stdlib.h>
#define int long long
#define maxn 2000010
int kun[maxn], hun[maxn], left[maxn], right[maxn];
int anser = 999999999999999, r = 0, l = 214748364, mid;

int sum1[maxn] = {0}, sum2[maxn] = {0};
int n, m, s, x, y, sum;

int check(int x) {
    for (int i = 1; i <= n; i++) {
        if (kun[i] >= x) {
            sum1[i] = sum1[i - 1] + 1;
            sum2[i] = sum2[i - 1] + hun[i];
        } else {
            sum1[i] = sum1[i - 1];
            sum2[i] = sum2[i - 1];
        }
    }
    int h = 0;
    for (int i = 1; i <= m; i++)
        h += (sum1[right[i]] - sum1[left[i] - 1]) * (sum2[right[i]] - sum2[left[i] - 1]);
    sum = abs(h - s);
    if (h > s)
        return 1;
    return 0;
}

main() {
    scanf("%lld%lld%lld", &n, &m, &s);
    for (int i = 1; i <= n; i++) {
        scanf("%lld %lld", &kun[i], &hun[i]);
        r = r > kun[i] ? r : kun[i];
        l = l < kun[i] ? l : kun[i];
    }
    for (int i = 1; i <= m; i++) {
        scanf("%lld%lld", &left[i], &right[i]);
    }
    l -= 1, r += 2;
    while (l <= r) {
        mid = (l + r) >> 1;
        if (check(mid)) { //检查该值是否小于上一值
            l = mid + 1;
        } else
            r = mid - 1 ;
        anser = anser < sum ? anser : sum;
    }
    anser = anser < sum ? anser : sum;
    printf("%lld", anser);
    return 0;
}

by wzhm54nr @ 2024-03-12 23:43:06

main 函数返回值原因导致的UB?


by ogagnin @ 2024-03-13 08:09:50

@xjstud abs(h - s) 的反回值和传入参数都是 int 而不是 long long


by xyjstud @ 2024-03-13 13:01:28

@ogagnin 确实是这个原因,我把abs函数换成if(sum<0)sum=-sum;就可以了


by xyjstud @ 2024-03-13 13:01:55

感谢各位大佬hh


|