【題解】ZeroJudge d547: 4. 秘密(secrets)

【題目敘述】https://zerojudge.tw/ShowProblem?problemid=d547

#include <iostream>
#include <sstream>
#include <algorithm>
#include <vector>
using namespace std;
 
int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    int N, M;
    cin >> N >> M;

    int passwd[M];
    for (int i = 0; i < M; i++){
        cin >> passwd[i];
    }
    string s;
    getline(cin, s);
    
    while (N--){
        getline(cin, s);
        stringstream ss(s);
        int x;
        vector<int> num, check;
        while (ss >> x){
            num.push_back(x);
        }
        int n1 = -1, n2 = -1;
        for (int j = M; j > 0; j--){
            if (n1 == -1){
                n1 = num[j];
            } else {
                n1 = abs(num[j+1] - num[j]);
            }
            n2 = num[j-1];
            if (n1 < n2){
                check.push_back(0);
            } else {
                check.push_back(1);
            }
        }
        reverse(check.begin(), check.end());
        bool flag = true;
        for (int j = 0; j < M; j++){
            if (check[j] != passwd[j]){
                flag = false;
                break;
            }
        }
        if (flag){
            for (auto i: num){
                cout << i << " ";
            }
            cout << "\n";
        }
    }
    return 0;
}

Python code (credit: Amy Chou)

N, M = map(int, input().split())
passwd = list(map(int, input().split()))

for i in range(N):
    num = list(map(int, input().split()))
    check = []
    n1 = None
    for j in range(M, 0, -1):
        if n1 is None:
            n1 = num[j]
        else:
            n1 = abs(num[j+1] - num[j])
        n2 = num[j-1]
        if (n1 < n2):
            check.append(0)
        else:
            check.append(1)
    check.reverse()
    if (check == passwd):
        print(' '.join(map(str, num)))
分享本文 Share with friends