题解:UVA124 Following Orders

考虑深搜和拓扑排序。从入度为零的节点开始,逐步添加到当前的排列结果中,并在每一步递减相邻节点的入度。如果某个节点的入度变为零,就递归地将其添加到当前排列中。一旦达到排列的叶节点,就存储起来,并按字典顺序排序。

代码:

#include<bits/stdc++.h>
using namespace std;

void readVar(map<char,string>&graph,map<char,int>&inedge,string&input);
void mr(map<char,string>&graph,map<char,int>&inedge,string&input);
void alltopsort(map<char,string>&graph,map<char,int>&inedge);
void gettopsort(map<char,string>&graph,map<char,int>inedge,map<char,bool>visited,char start,set<string>&topos,string result);

int main(){
	string input;
	bool new_line=false;
	while(getline(std::cin,input)){
		if(new_line)cout<<endl;
		new_line=1;
		map<char,string>graph;
		map<char,int>inedge;
		readVar(graph,inedge,input);
		getline(std::cin,input);
		mr(graph,inedge,input);
		alltopsort(graph,inedge);
	}
	return 0;
}
void readVar(map<char,string>&graph,map<char,int>&inedge,string&input){
	stringstream ss(input);
	char tmp;
	string str;
	while(ss>>tmp){
		graph[tmp]=str;
		inedge[tmp]=0;
	}
	return;
}
void mr(map<char,string>&graph,map<char,int>&inedge,string&input){
	stringstream ss(input);
	char tmp1,tmp2;
	while(ss>>tmp1){
		ss>>tmp2;
		graph[tmp1].push_back(tmp2);
		++inedge[tmp2];
	}
	return;
}

void alltopsort(map<char,string>&graph,map<char,int>&inedge){
	set<string>topos;
	map<char,bool>visited;
	for(auto a:inedge)
		visited[a.first]=false;

	for(auto a:inedge)
		if(a.second==0)
			gettopsort(graph,inedge,visited,a.first,topos,"");
	for(auto a:topos)
		cout<<a<<endl;
	return;
}
void gettopsort(map<char,string>&graph,map<char,int>inedge,map<char,bool>visited,char start,set<string>&topos,string result){
	result=result+start;
	visited[start]=true;
	for(auto a:graph[start])
		inedge[a]--;
	bool leaf=true;
	for(auto a:inedge)
		if(!visited[a.first]&&a.second==0){
			leaf=false;
			gettopsort(graph,inedge,visited,a.first,topos,result);
		}
	if(leaf) topos.insert(result);
	return;
}
posted @ 2024-10-02 17:44  cly312  阅读(14)  评论(0)    收藏  举报