题解:P15359 「WYZOI R2」春运

· · 题解

思路:

数学题。先考虑暴力,很显然直接枚举天数模拟就行了,但 t\le10^{18},这样做无法通过,考虑优化。注意到指令数组是有循环周期性的。它每 m 天向右转一格,总共 n 条指令,所以循环节长度为 n\times m 天。于是我们可以先处理出 n\times m 天行走的路程 len,然后利用周期性,把 t 天分为 \left\lfloor\dfrac{t}{n\times m}\right\rfloor 个长度为 n\times m 天的循环和单独的一个长度为 t \bmod n\times m 天的剩余部分。循环的部分乘起来就行,答案为 (\left\lfloor\dfrac{t}{n\times m}\right\rfloor\times len)\bmod d。最后加上剩余部分的答案 lens,结果就是 (\left\lfloor\dfrac{t}{n\times m}\right\rfloor\times len+lens)\bmod d。最后提醒一下,注意取模!

代码:

#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N = 3e3+10;
int d, n, m, t;
int ans;
int a[N];
signed main() {
    cin >> d >> n >> m >> t;

    for (int i = 0; i < n; i++) {
        cin >> a[i];
    }

    for (int i = 0; i < n * m; i++) {
        if (i % m == 0) {
            int x = a[n - 1];

            for (int j = n - 1; j >= 0; j--) {
                a[j] = a[j - 1];
            }

            a[0] = x;
        }

        ans = (ans + a[i % n]) % d;
    }

    ans = ((ans % d) * (t / (n * m) % d) % d) % d;
    t %= (n * m);

    for (int i = 0; i < t; i++) {
        if (i % m == 0) {
            int x = a[n - 1];

            for (int j = n - 1; j >= 0; j--) {
                a[j] = a[j - 1];
            }

            a[0] = x;
        }

        ans = (ans + a[i % n]) % d;
    }

    cout << ans % d;
    return 0;
}