CF Round#290 C - Fox And Names
C - Fox And Names
拓扑排序
要自定义字典序使给出的字符串是按字典序递增的顺序
可对于前后两个字符串可找到一组字母间的关系,转化为差分约束问题
#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
#include <cmath>
#include <queue>
using namespace std;
typedef long long ll;
const int N = 110, M = 26;
vector<int> G[M];
int din[M];
string s[N];
int n;
int f[M];
struct Node
{
char ch;
int val;
bool operator<(const Node &x) const
{
return val < x.val;
}
}c[M];
void add(int a, int b)
{
G[a].push_back(b);
din[b]++;
}
void topsort()
{
queue<int> q;
int cnt = M;
for (int i = 0; i < M; i++)
if (!din[i])
q.push(i);
while(!q.empty())
{
int u = q.front();
q.pop();
cnt--;
for (auto v : G[u])
{
f[v] = max(f[v], f[u] + 1);
din[v]--;
if (!din[v])
q.push(v);
}
}
if (cnt)
{
cout << "Impossible" << endl;
return;
}
for (int i = 0; i < M; i++)
{
char ch = i + 'a';
c[i] = {ch, f[i]};
}
sort(c, c + M);
for (int i = 0; i < M; i++)
{
if (i < c[i].val)
{
cout << "Impossible" << endl;
return;
}
}
for (int i = 0; i < M; i++)
cout << c[i].ch;
cout << endl;
}
int main()
{
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
cin >> n;
for (int i = 1; i <= n; i++)
cin >> s[i];
for (int i = 2; i <= n; i++)
{
int len = min(s[i].length(), s[i-1].length());
bool flag = false;
for (int j = 0; j < len; j++)
{
if (s[i][j] != s[i-1][j])
{
int a = s[i-1][j] - 'a';
int b = s[i][j] - 'a';
add(a, b);
flag = true;
break;
}
}
if (!flag && s[i-1] != s[i] && s[i].length() < s[i-1].length())
{
cout << "Impossible" << endl;
return 0;
}
}
topsort();
return 0;
}