Following Orders(POJ 1270)

题目链接

题目描述

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.

输入格式

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.

输出格式

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

输出样例

abfg
abgf
agbf
gabf

wxzvy
wzxvy
xwzvy
xzwvy
zwxvy
zxwvy

分析

题目大意共有多组测试,每组测试有两行。第一行给出顶点变量,第二行每两个变量x和y表示x<y,要求按照字典序输出所有满足要求的拓扑序列。
显然根据拓扑排序思想用回溯法求出所有序列并输出。

源程序

//#include <bits/stdc++.h>	//poj不能用万能头
#include <cstdio>
#include <cstring>
#define MAXN  30
using namespace std;
char str[1005];
int n,in[MAXN],path[MAXN];
bool g[MAXN][MAXN],flag[MAXN],used[MAXN];
void dfs(int cnt)
{
	if(cnt==n+1){
		for(int i=1;i<=n;i++)
			printf("%c",path[i]+'a');
		printf("\n");
	}
	for(int i=0;i<26;i++){
		if(flag[i]&&!used[i]&&!in[i]){
			for(int j=0;j<26;j++)
				if(g[i][j])in[j]--;
			used[i]=true;
			path[cnt]=i;
			dfs(cnt+1);
			used[i]=false;
			for(int j=0;j<26;j++)
				if(g[i][j])in[j]++;
		}
	}
}
int main()
{
	while(gets(str)){
		memset(g,false,sizeof(g));
		n=0;
		for(int i=0;i<=26;i++)in[i]=flag[i]=used[i]=0;	//初始化
		for(int i=0;str[i];i++){
			if(str[i]!=' '){
				flag[str[i]-'a']=true;
				n++;
			}
		} 
		gets(str);
		for(int i=0;str[i];i++){
			if(str[i]!=' '){
				int x=str[i]-'a',y=str[i+2]-'a';
				i=i+2;
				if(g[x][y])continue;	//重边 
				g[x][y]=true;
				in[y]++;
			}
		}
		dfs(1);
		printf("\n");
	}
}
发布了19 篇原创文章 · 获赞 0 · 访问量 128

猜你喜欢

转载自blog.csdn.net/weixin_43960284/article/details/105251110