top1编程
← 返回题目
题解

【入门】数数游戏

1 条题解

  • 0
    @ 2026-7-29 0:17:23
    #include <iostream>
    using namespace std;
    
    int main() {
        int n;
        cin >> n;
    
        int a[10];  // n <= 10
        for (int i = 0; i < n; i++) {
            cin >> a[i];
        }
    
        int error_pos = -1;
    
        // 从第3项开始检查(索引从2开始)
        for (int i = 2; i < n; i++) {
            if (a[i] != a[i-1] + a[i-2]) {
                error_pos = i + 1;  // 位置从1开始
                break;
            }
        }
    
        // 修复数列:从错误位置开始,按正确规则重建
        // 注意:前面的数不变,从错误位置开始重建
        for (int i = 2; i < n; i++) {
            if (i == error_pos - 1) {
                // 当前是第一个错误的位置,应等于前两项之和
                a[i] = a[i-1] + a[i-2];
            } else if (i > error_pos - 1) {
                // 后续所有项都按规则计算
                a[i] = a[i-1] + a[i-2];
            }
        }
    
        // 输出结果
        cout << error_pos << endl;
        for (int i = 0; i < n; i++) {
            if (i == 0) cout << a[i];
            else cout << " " << a[i];
        }
        cout << endl;
    
        return 0;
    }
    
    • 1