題解:UVA124 Following Orders

cly312發表於2024-10-02

考慮深搜和拓撲排序。從入度為零的節點開始,逐步新增到當前的排列結果中,並在每一步遞減相鄰節點的入度。如果某個節點的入度變為零,就遞迴地將其新增到當前排列中。一旦達到排列的葉節點,就儲存起來,並按字典順序排序。

程式碼:

#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;
}

相關文章