標籤:圖論 dfs acm poj algorithm
來源: http://poj.org/problem?id=1270
Following Orders
| Time Limit: 1000MS |
|
Memory Limit: 10000K |
| Total Submissions: 3812 |
|
Accepted: 1512 |
Description
Order is an important concept in mathematics and in computer science. For example, Zorn‘s Lemma states: ``a partially ordered set in which every chain has an upper bound contains a maximal element.‘‘ Order is also important in reasoning about the fix-point semantics of programs.
This problem involves neither Zorn‘s Lemma nor fix-point semantics, but does involve order.
Given a list of variable constraints of the form x < y, you are to write a program that prints all orderings of the variables that are consistent with the constraints.
For example, given the constraints x < y and x < z there are two orderings of the variables x, y, and z that are consistent with these constraints: x y z and x z y.
Input
The input consists of a sequence of constraint specifications. A specification consists of two lines: a list of variables on one line followed by a list of contraints on the next line. A constraint is given by a pair of variables, where x y indicates that x < y.
All variables are single character, lower-case letters. There will be at least two variables, and no more than 20 variables in a specification. There will be at least one constraint, and no more than 50 constraints in a specification. There will be at least one, and no more than 300 orderings consistent with the contraints in a specification.
Input is terminated by end-of-file.
Output
For each constraint specification, all orderings consistent with the constraints should be printed. Orderings are printed in lexicographical (alphabetical) order, one per line.
Output for different constraint specifications is separated by a blank line.
Sample Input
a b f ga b b fv w x y zv y x v z v w v
Sample Output
abfgabgfagbfgabfwxzvywzxvyxwzvyxzwvyzwxvyzxwvy
Source
Duke Internet Programming Contest 1993,uva 124
題意:在給出的約束條件下對字母進行排序。
題解: DFS+拓撲排序~~ 儲存每個節點的入度,辺的起點和終點通過第二行輸入的約束條件索引即可。
AC代碼:
#include<iostream>#include<string>#include<cstring>using namespace std;const int Max=30;string var,req;bool visit[Max];int pre[Max],len1,len2;void dfs(int k,string s){if(k==(len1+1)/2){cout<<s<<endl;return ;}for(int i=0;i<26;i++){if(visit[i]&&!pre[i]){visit[i]=false;for(int t=0;t<len2;t+=4){if(i==req[t]-'a')--pre[req[t+2]-'a'];}dfs(k+1,s+(char)(i+'a'));visit[i]=true;for(int t=0;t<len2;t+=4){if(i==req[t]-'a')++pre[req[t+2]-'a'];}}}}int main(){while(getline(cin,var)){getline(cin,req);len1=var.size(); len2=req.size();memset(visit,0,sizeof(visit));memset(pre,0,sizeof(pre));for(int i=0;i<len1;i+=2)visit[var[i]-'a']=true;for(int i=2;i<len2;i+=4)pre[req[i]-'a']++;dfs(0,""); cout<<endl;}return 0;}