Codeforces Round #290 (Div. 1) A. Fox And Names

建出图,按入度进行广搜就行。。。。

#include <iostream>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <bitset>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <climits>
#include <cstdlib>
#include <cmath>
#include <time.h>
#define maxn 105
#define maxm 200005
#define eps 1e-7
#define mod 1000000007
#define INF 0x3f3f3f3f
#define PI (acos(-1.0))
#define lowbit(x) (x&(-x))
#define mp make_pair
#define ls o<<1
#define rs o<<1 | 1
#define lson o<<1, L, mid 
#define rson o<<1 | 1, mid+1, R
#define pii pair<int, int>
#pragma comment(linker, "/STACK:16777216")
typedef long long LL;
typedef unsigned long long ULL;
using namespace std;
LL qpow(LL a, LL b){LL res=1,base=a;while(b){if(b%2)res=res*base;base=base*base;b/=2;}return res;}
LL powmod(LL a, LL b){LL res=1,base=a;while(b){if(b%2)res=res*base%mod;base=base*base%mod;b/=2;}return res;}
//head

struct Edge
{
	int v;
	Edge *next;
}*H[maxn], E[maxm], *edges;

char p[maxn];
char s[maxn];
bool vis[maxn];
int in[maxn];
queue<int> q;
vector<int> ans;
int n, ok;

void addedges(int u, int v)
{
	edges->v = v;
	edges->next = H[u];
	H[u] = edges++;
}

void init()
{
	edges = E;
	memset(H, 0, sizeof H);
}

void work()
{
	ok = 1;
	scanf("%d%s", &n, p);
	for(int i = 2; i <= n; i++) {
		scanf("%s", s);
		int lenp = strlen(p);
		int lens = strlen(s);
		int flag = 0;
		for(int j = 0; s[j] && p[j]; j++) {
			if(s[j] == p[j]) continue;
			else {
				addedges(p[j] - 'a', s[j] - 'a');
				flag = 1;
				in[s[j] - 'a']++;
				break;
			}
		}
		if(flag == 0 && lenp > lens) ok = 0;
		memcpy(p, s, sizeof s);
	}
	if(!ok) {
		printf("Impossible\n");
		return;
	}
	for(int i = 0; i < 26; i++) if(!in[i]) q.push(i);
	while(!q.empty()) {
		int u = q.front();
		q.pop();
		ans.push_back(u);
		for(Edge *e = H[u]; e; e = e->next) {
			in[e->v]--;
			if(in[e->v] == 0) q.push(e->v);
		}
	}
	if(ans.size() != 26) {
		printf("Impossible\n");
		return;
	}
	for(int i = 0; i < ans.size(); i++) printf("%c", ans[i] + 'a');
	printf("\n");
}

int main()
{
	init();
	work();
		
	return 0;
}


你可能感兴趣的:(codeforces)