zoukankan      html  css  js  c++  java
  • POJ1270 拓扑排序

    解析:

    我拿这题来练习拓扑排序相关知识。《数据结构编程实验》中给的是Java解法,虽然我正准备学Java,但是目前却还是只会用c++解题。这次解题我很依赖STL,用到了map、vector、string等类,并以此为基础,虽然我本意是想让代码更简洁,可读性更强,但是好像弄巧成拙了,修修改改代码可读性已经变得极差了。

    其中遇到了两个问题:

    • 第一:双vector,即vector < vector<int> > v(25),如果想初始化,不可以直接写v.clear();而是要用for循环,把每一个元素都clear(),如for(int i = 0;i < v.size() , i++)       v[i].clear();
    • 第二个问题,一如既往的是字典序问题,因为样例给的数据就算不排序也是按照字典序输出的,所以我忽略了这点,另一个原因就是我不太想读英文。以后这点细节需要注意。

    代码实例:

    #include<iostream>
    #include<map>
    #include<vector>
    #include<cstring>
    #include<string>
    #include<algorithm>
    using namespace std;
    typedef vector<int> vec;
    vector<vec> Next(25);
    vector<string> t_ans;
    map<char,int> m;
    bool has[25] = {false};
    int pre[25] = {0};
    int cnt = 0;
    char ans[25];
    inline int getID(char c){
    	if(m.count(c) == 0)		m[c] = cnt++;
    	return m[c];
    }
    void init(){
    	memset(pre,0,sizeof pre);
    	memset(has,false,sizeof has);
    	t_ans.clear();
    	m.clear();
    	for(int i = 0;i < 25;i++)
    		Next[i].clear();
    	cnt = 0;
    }
    void dfs(string a,int step){
    	if(step == cnt){
    		string t;
    		for(int i = 0;i < cnt;i++)	t += ans[i];
    		t_ans.push_back(t);
    		return;
    	}
    	for(int i = 0;i < a.length();i += 2){
    		if(has[i] == false)	continue;
    		int id = getID(a[i]);
    		if(pre[id] == 0){
    			ans[step] = a[i];
    			for(int j = 0;j < Next[id].size();j++)
    				pre[Next[id][j]]--;
    			has[i] = false;
    			dfs(a,step+1);
    			has[i] = true;
    			for(int j = 0;j < Next[id].size();j++)
    				pre[Next[id][j]]++;
    		}
    	}
    }
    int main()
    {
    	string str;
    	while(getline(cin,str)){
    		//cout << str << endl;
    		string str2;
    		getline(cin,str2);
    		//cout << str2 << endl;
    		init();
    		int len = str.length();
    		int len2 = str2.length();
    		for(int i = 0;i < len; i += 2){
    			getID(str[i]);
    			has[i] = true;
    		}
    		for(int i = 0;i < len2-2;i += 4){
    			int id1 = getID(str2[i]);
    			int id2 = getID(str2[i+2]);
    			Next[id1].push_back(id2);
    			pre[id2]++;
    		}
    		dfs(str,0);
    		sort(t_ans.begin(),t_ans.end());
    		for(int i = 0;i < t_ans.size();i++)	cout << t_ans[i] << endl;
    		cout << endl;
    	}	
    	return 0;
    }
  • 相关阅读:
    谎言,
    happy,
    架构,
    休闲游戏随想,
    IOS响应者链
    application 几个方法
    ios block 循环引用
    洛谷 P 1133 教主的花园
    Codevs 1148 == 洛谷 P1057 传球游戏
    Codevs 1169 == 洛谷 P1006 传纸条
  • 原文地址:https://www.cnblogs.com/long98/p/10352208.html
Copyright © 2011-2022 走看看