1. 程式人生 > 其它 >CF Round#290 C - Fox And Names

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;
}