裸的topsort,结果在终判时挂了,就因为没有特判,杯具。。。。
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <string>
#include <queue>
#define maxn 111
using namespace std;
int indegree[maxn],path[maxn];
int n,m;
char w[105][105];
queue<int>Q;
vector<int>edges[10000];
void topsort()
{
memset(path,0,sizeof(path));
while (!Q.empty())
Q.pop();
for (int i=0;i<26;i++)
if (!indegree[i])
Q.push(i);
int num=0;
while (!Q.empty())
{
int now=Q.front();
Q.pop();
path[num++]=now;
for (int i=0;i<edges[now].size();i++)
{
--indegree[ edges[now][i]];
if (!indegree[ edges[now][i] ])
{
Q.push(edges[now][i]);
}
}
}
if (num<26)
{
printf("Impossible\n");
return ;
}
for (int i=0;i<num;i++)
printf("%c",path[i]+'a');
printf("\n");
}
int main()
{
while (~scanf("%d",&n))
{
memset(indegree,0,sizeof(indegree));
for (int i=1;i<=n;i++)
edges[i].clear();
int u,v;
for (int i=0;i<n;i++)
scanf("%s",w[i]);
int flag=0;
for (int i=1;i<n;i++)
{
int a=i-1,b=i;
int la=strlen(w[a]);
int lb=strlen(w[b]);
int aa=0,bb=0;
while (aa<la&&bb<lb&&w[a][aa]==w[b][bb])
{
aa++;
bb++;
}
if (bb==lb&&aa<la) {flag=1; break;} //掉了这一句,结果挂了。。。
if (aa==la&&bb<=lb) continue;
indegree[w[b][bb]-'a']++;
edges[w[a][aa]-'a'].push_back(w[b][bb]-'a');
}
if (flag)
{
printf("Impossible\n");
continue;
}
topsort();
}
return 0;
}