#290 (div.2) C. Fox And Names
来源:互联网 发布:怎么做网络推广赚钱 编辑:程序博客网 时间:2024/04/30 21:51
1.题目描述:点击打开链接
2.解题思路:本题利用拓扑排序解决。本题要求出一个a~z的排列,使得所有名字按照这样的“字典序”是逐渐增加的。显然这里存在着字母之间的大小关系,容易联想到拓扑排序。
那么该如何来排序呢?先思考一下简单的情况,假设姓名s,t是相邻的两个名字,如果s是t的一个前缀,那么跳过即可;反之如果t是s的前缀,那么肯定是无解的。如果不是以上这种情况,那么首个不相同的位置处的两个字母就可以连一条边,最终构建出一个有向图。最后利用拓扑排序的模板,为26个英文字母从后向前排序即可。
3.代码:
#define _CRT_SECURE_NO_WARNINGS #include<iostream>#include<algorithm>#include<string>#include<sstream>#include<set>#include<vector>#include<stack>#include<map>#include<queue>#include<deque>#include<cstdlib>#include<cstdio>#include<cstring>#include<cmath>#include<ctime>#include<functional>using namespace std;#define N 110char s[N][N];int g[26][26];int c[26], topo[26], t;int n;bool dfs(int u){c[u] = -1;for (int v = 0; v < 26;v++)if (g[u][v]){if (c[v] < 0)return false;if (!c[v] && !dfs(v))return false;}c[u] = 1;topo[--t] = u;return true;}bool toposort(){t = 26;memset(c, 0, sizeof(c));memset(topo, 0, sizeof(topo)); for (int i = 25; i >=0;i--)//注意,一定要从后往前来寻找if (!c[i])if (!dfs(i))return false;return true;}int main(){//freopen("t.txt", "r", stdin);while (~scanf("%d", &n)){memset(g, 0, sizeof(g));for (int i = 0; i < n; i++)scanf("%s", s[i]);for (int i = 0; i < n - 1; i++){int l1 = strlen(s[i]);int l2 = strlen(s[i + 1]);int p = 0;while (p < min(l1, l2) && s[i][p] == s[i + 1][p])p++;if (p == l1&&l1 < l2)continue;//如果s[i]是s[i+1]的前缀,那么跳过if (p == l2&&l2 < l1){ puts("Impossible"); goto x1; }//反之,一定无解if (g[s[i][p] - 'a'][s[i + 1][p] - 'a'])continue;g[s[i][p] - 'a'][s[i + 1][p] - 'a'] = 1;//建立有向图}if (toposort()){for (int i = 0; i < 26; i++)printf("%c", topo[i] + 'a');puts("");}else puts("Impossible");x1:;}return 0;}
0 0
- #290 (div.2) C. Fox And Names
- C. Fox And Names Codeforces Round #290 (Div. 2)
- C. Fox And Names(Codeforces Round #290 (Div. 2))
- Codeforces Round #290 (Div. 2) C. Fox And Names
- Codeforces Round #290 (Div. 2) C题Fox And Names
- Codeforces Round #290 (Div. 2)-C. Fox And Names
- Codeforces Round #290 (Div. 2) C. Fox And Names && D. Fox And Jumping
- Codeforces Round #290 (Div. 2)C. Fox And Names(拓扑排序)
- Codeforces Round #290 (Div. 2)C - Fox And Names——拓扑排序
- Codeforces Round #290 (Div. 2) C. Fox And Names 拓扑排序
- Codeforces Round #290 (Div. 2) C. Fox And Names 拓扑排序
- Codeforces Round #290 (Div. 2) C. Fox And Names 拓扑排序
- Codeforces Round #290 (Div. 2) - C. Fox And Names(最短路)
- Codeforces Round #290 (Div. 2) - C. Fox And Names (拓扑排序)
- 拓扑排序——Codeforces Round #290 (Div. 2) C. Fox And Names
- CF 290Div2 C Fox And Names
- codeforces 290div2 C.Fox And Names
- CF C. Fox And Names
- 冒泡排序的C++实现
- Eddy's digital Roots
- RFC3581——SIP中的rport机制
- [leetcode]Rotate Array
- 【数据结构与算法分析(一)】排序
- #290 (div.2) C. Fox And Names
- hdu 5203 Rikka with wood sticks
- 今天继续学习锋利的JQuery,第三章后半段
- Shell编程入门总结(正则表达式篇)
- ctags for systemverilog(vim用)
- Linux 2.6 Completely Fair Scheduler 内幕
- 【Java二十周年】我的JAVA小时代
- java动态代理机制分析
- Hive安装