为什么要 + mod

P11362 [NOIP2024] 遗失的赋值

FwbAway @ 2024-12-08 11:13:55

#include <bits/stdc++.h>
#define int long long
using namespace std;
const int N = 110000;
const int mod = 1e9 + 7; 
int t, n, m, v, ans;
struct node {
    int c, d;
}a[N];
bool cmp(node x, node y) {
    return x.c != y.c ? x.c < y.c : x.d < y.d;
}
inline int P(int x, int y) {
    int ans = 1;
    while (y) {
        if (y & 1) ans = ans * x % mod;
        x = x * x % mod;
        y >>= 1;
    }
    return ans;
}
signed main() {
    scanf("%lld", &t);
    while (t--) {
        ans = 0;
        scanf("%lld%lld%lld", &n, &m, &v);
        for (int i = 1; i <= m; i++) {
            scanf("%lld%lld", &a[i].c, &a[i].d);
        }
        sort(a + 1, a + m + 1, cmp);
        int flag = 0;
        for (int i = 1; i < m; i++) {
            if (a[i].c == a[i + 1].c && a[i].d != a[i + 1].d) {
                flag = 1;
                break;
            }
        }
        if (flag) {
            printf("0\n");
            continue;
        }
        ans = P(v, 2 * a[1].c - 2);
        for (int i = 1; i < m; i++) {
            if (a[i].c == a[i + 1].c) continue;
            int l = a[i + 1].c - a[i].c;
            ans = ans * ((P(v, 2 * l) - P(v, l - 1) * (v - 1) % mod) % mod + mod) % mod;
        }
        ans = ans * P(v, 2 * n - 2 * a[m].c);
        printf("%lld\n", ans % mod);
    }
    return 0;
}

看这一行:ans = ans * ((P(v, 2 * l) - P(v, l - 1) * (v - 1) % mod) % mod + mod) % mod;,为什么会有一个 +mod,怎么会是负数呢?

没有这个就 65pts,加上就 AC 了。


by Laihaocheng @ 2024-12-08 11:15:30

c++的取模跟数学上的取模不一样


by FwbAway @ 2024-12-08 11:21:58

@Laihaocheng 怎讲


by SleepWithMiku @ 2024-12-08 11:22:31

P(v, 2 l) 取模完不一定比 P(v, l - 1) (v - 1) 大


by FwbAway @ 2024-12-08 11:34:03

@SleepWithMiku明白了,感谢感谢


|