CF510C

题目连接:CodeForces - 510C

 补题系列。。。拓扑排序

 1 #include<bits/stdc++.h>
 2 #include<cstdio>
 3 #include<cstring>
 4 using namespace std;
 5 const int maxn=100010;
 6 int n;
 7 struct edge
 8 {
 9     int v,nex;
10 }e[maxn];
11 int head[maxn];
12 int cnt;
13 int deg[maxn]; //入度
14 char s[110][110];
15 char ans[110],ct;
16 int q[110],top;
17 void add(int u,int v)
18 {
19     e[cnt].v=v;
20     e[cnt].nex=head[u];
21     head[u]=cnt++;
22     deg[v]++;
23 }
24 void init()
25 {
26     cnt=top=ct=0;
27     memset(head,-1,sizeof(head));
28     memset(deg,0,sizeof(deg));
29 }
30 int main()
31 {
32     scanf("%d",&n);
33     for(int i=0;i<n;i++)
34         scanf("%s",s[i]);
35     init();
36     for(int i=0;i+1<n;i++)
37     {
38         int len1=strlen(s[i]);
39         int len2=strlen(s[i+1]);
40         bool fd=0;
41         for(int j=0;j<len1&&j<len2;j++)
42             if(s[i][j]!=s[i+1][j])
43             {
44                 fd=1;
45                 add(s[i][j]-'a',s[i+1][j]-'a');
46                 break;
47             }
48         if(!fd&&len1>len2)
49         {
50             puts("Impossible");
51             return 0;
52         }
53     }
54     for(int i=0;i<26;i++) if(deg[i]==0)  //
55     {
56         q[++top]=i;
57         deg[i]=-1;
58     }
59     while(top>0)
60     {
61         int u=q[top--];
62         ans[ct++]='a'+u;
63         for(int i=head[u];i!=-1;i=e[i].nex)
64         {
65             int v=e[i].v;
66             deg[v]--;
67             if(deg[v]==0)
68             {
69                 deg[v]=-1;
70                 q[++top]=v;
71             }
72         }
73     }
74     for(int i=0;i<26;i++)
75         if(deg[i]>=0)
76     {
77         puts("Impossible");
78         return 0;
79     }
80     ans[ct]=0;
81     puts(ans);
82     return 0;
83 }
原文地址:https://www.cnblogs.com/yijiull/p/6809885.html