题解: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 @   cly312  阅读(1)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示