UVA 12604 - Caesar Ciphe

UVA 12604 - Caesar Cipher

题意:给一个字母表s,一个标准串w,一个密文s,问w是否可能在密文的原文中出现且仅出现一次

#include <bits/stdc++.h>

using namespace std;

const int maxn = 6e5;
char a[maxn], b[maxn], o[maxn];
int c[300];
int pi[maxn], f[maxn];

void getnext(int n) {
    pi[1] = 0;
    for (int i = 2, j = 0; i <= n; i++) {
        while (j > 0 && a[i] != a[j + 1]) j = pi[j];
        if (a[i] == a[j + 1]) j++;
        pi[i] = j;
    }
}

bool solve(int n, int m) {
    int flag = 0;
    for (int i = 1, j = 0; i <= m; i++) {
        while (j > 0 && (j == n || b[i] != a[j + 1])) j = pi[j];
        if (b[i] == a[j + 1]) j++;
        f[i] = j;
        if (f[i] == n) {
            flag++;
        }
    }
    return flag == 1;
}

vector<int> ans;

int main() {
//    freopen("in.txt", "r", stdin);
//    freopen("out.txt", "w", stdout);
    int _;
    scanf("%d", &_);
    char s[100];
    while (_--) {
        ans.clear();
        memset(c, 0, sizeof(c));
        scanf("%s %s %s", s, o + 1, b + 1);
        int na = strlen(o + 1), nt = strlen(b + 1);
        int ns = strlen(s);
        for (int i = 0; i < ns; i++) {
            c[s[i]] = i;
        }
        int cnt = 0;
        for (int k = 0; k < ns; k++) {
            for (int i = 1; i <= na; i++) {
                a[i] = s[(c[o[i]] + k) % ns];
            }
            a[na + 1] = '\0';
            getnext(na);
            if (solve(na, nt))
                ans.push_back(k), cnt++;
        }
        if (cnt == 0) printf("no solution\n");
        else if (cnt == 1) printf("unique: %d\n", ans[0]);
        else {
            printf("ambiguous:");
            for (auto v:ans) {
                printf(" %d", v);
            }
            printf("\n");
        }
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/albert-biu/p/11307312.html