[CF508D] Tanya and Password - 欧拉通路,hash


[CF508D] Tanya and Password - 欧拉通路,hash

Description

有一个长度为 \(n+2\) 的字符串 \(S\),现在给你 \(S[1..3],S[2..4],...,S[n,n+2]\),但是是打乱顺序的,你需要构造出 \(S\)

Solution

将每个给定的串 \(s[1..3]\) 的转化为图上的一条边 \(H(s[1],s[2]) \to H(s[2],s[3])\),然后跑欧拉通路即可

#include 
using namespace std;

#define int long long

const int M = 128;
const int N = 100005;

int n;
vector g[N];
vector ans;
int din[N], dout[N];

void dfs(int p)
{
    while (g[p].size())
    {
        int q = g[p].back();
        g[p].pop_back();
        dfs(q);
    }
    ans.push_back(p);
}

signed main()
{
    ios::sync_with_stdio(false);

    cin >> n;
    for (int i = 1; i <= n; i++)
    {
        string s;
        cin >> s;
        g[s[0] * M + s[1]].push_back(s[1] * M + s[2]);
        dout[s[0] * M + s[1]]++;
        din[s[1] * M + s[2]]++;
    }

    map mp;

    for (int i = 1; i <= M * M; i++)
        mp[din[i] - dout[i]]++;

    if (!((mp.size() == 1) || (mp.size() == 3 && mp[1] == 1 && mp[-1] == 1)))
    {
        cout << "NO" << endl;
    }
    else
    {
        int start = 0;
        for (int i = 1; i <= M * M; i++)
            if (dout[i])
                start = i;
        for (int i = 1; i <= M * M; i++)
            if (dout[i] - din[i] == 1)
                start = i;
        dfs(start);

        if (ans.size() != n + 1)
        {
            cout << "NO" << endl;
            return 0;
        }
        cout << "YES" << endl;

        for (int i = ans.size() - 1; i >= 0; i--)
            cout << (char)(ans[i] / M);
        cout << (char)(ans[0] % M) << endl;
    }
}

相关