Project Euler Problem 79: Passcode derivation【拓撲排序】

PE其他解題報告請參考這裏,本題答案在留言首條

Passcode derivation

Problem 79


A common security method used for online banking is to ask the user for three random characters from a passcode. For example, if the passcode was 531278, they may ask for the 2nd, 3rd, and 5th characters; the expected reply would be: 317.

The text file, keylog.txt, contains fifty successful login attempts.

Given that the three characters are always asked for in order, analyse the file so as to determine the shortest possible secret passcode of unknown length.


題意:

讓你求儘可能短的密碼段,使得每個三位的密碼,都可以依次取出

分析:

很明顯這是一個拓撲排序的題,比如一個數字,123,只需要保證1在2前,1在3前,2在3前,因爲不知道原先都有哪些數字出現過,所以我這裏用了一個dig數組來存儲出現過的數字,然後拓撲排序的板子即可

參考代碼
#include<bits/stdc++.h>

using namespace std;

#define pb push_back

int ind[11];
vector<int> E[11];
bool dig[11];

int main(){
    for (int i = 0; i < 50; i++) {
        int x; cin >> x;
        int a = x / 100, b = x / 10 % 10, c = x % 10;
        dig[a] = dig[b] = dig[c] = 1;
        E[a].pb(b), E[a].pb(c), E[b].pb(c);
        ind[b]++, ind[c] += 2;
    }
    int cnt = 0;
    for (int i = 0; i < 10; i++) if (dig[i]) cnt++;
    string s;
    while (cnt) {
        int t = -1;
        for (int i = 0; i < 10; i++) {
            if (!ind[i] && dig[i]) {
                dig[i] = 0;
                cnt--;
                t = i;break;
            }
        }
        if (t == -1) {
            puts("No answer");return 0;
        }
        s += (char)('0' + t);
        for (auto it : E[t]) ind[it]--;
    }
    cout << s << endl;
    return 0;
}

閱讀好習慣:點贊 + 收藏~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章