题解:P16345 阿瓦的数列

· · 题解

题目分析、

一开始拿到这题,以为就是个简单的递推,后来看到了数据范围才觉得不对劲,按照普通的数组递推直接飞起来了。

#include <bits/stdc++.h>
using namespace std;
const long long N = 1e18 + 5;
long long a[N];
int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);cout.tie(0);
    int t;
    cin >> t;
    while (t--){
        memset(a,0,sizeof(a));
        long long n;
        cin >> a[1] >> a[2] >> n;
        for (int i = 3;i <= n;i++) a[i] = a[i - 1] * a[i - 2] % i;
        cout << a[n] << '\n';
    }
    return 0;
}

喜提 CE。

后来我想到,不一定要用数组实现递推,可以用几个变量代替一下,而且我甚至想到了一步一取模,最后写出了这个代码:

#include <bits/stdc++.h>
using namespace std;
int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);cout.tie(0);
    int t;
    cin >> t;
    while (t--){
        long long x,y,n;
        cin >> x >> y >> n;
        if (n == 1) cout << x << '\n';
        else if (n == 2) cout << y << '\n';
        else{
            for (int i = 3;i <= n;i++){
                int t = (x % i) * (y % i) % i;
                x = y;
                y = t;
            }
            cout << y << '\n';
        }
    }
    return 0;
}

喜提 TLE,而且居然只有 40 分。

根据题意来看,f_3 只能取 0 到 2 之间的整数,f_4 只能取 0 到 3 之间的整数,我们可以将 f_3 和 f_4 所有可能的组合全部枚举出来,发现从 i > 28 开始,以后 f_i 的取值就只能是 0 或 1 了,那我们只需要看看 f_29 和 f_30 的值就行了。至于 i < 28 嘛,直接暴力枚举就行了。

#include <bits/stdc++.h>
using namespace std;
int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);cout.tie(0);
    int t;
    cin >> t;
    while (t--){
        long long x,y,n;
        cin >> x >> y >> n;
        bool flag = 0;
        if (n == 1) cout << x << '\n';
        else if (n == 2) cout << y << '\n';
        else{
            for (int i = 3;i <= n;i++){
                int t = (x % i) * (y % i) % i;
                if (t == 0){
                    cout << 0 << '\n';
                    flag = 1;
                    break;
                }
                else if (t == 1 and y == 1){
                    cout << 1 << '\n';
                    flag = 1;
                    break;
                }
                x = y;
                y = t;
            }
            if (!flag) cout << y << '\n';
        }
    }
    return 0;
}