标签:图论 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 g
a b b f
v w x y z
v y x v z v w v
Sample Output
abfg
abgf
agbf
gabf
wxzvy
wzxvy
xwzvy
xzwvy
zwxvy
zxwvy
Source
题意:在给出的约束条件下对字母进行排序。
题解: 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;
}
POJ 1270 Following Orders,布布扣,bubuko.com
POJ 1270 Following Orders
标签:图论 dfs acm poj algorithm
原文地址:http://blog.csdn.net/mummyding/article/details/38532397