zoukankan      html  css  js  c++  java
  • Uva


    把小于关系看成有向边,就变成了一个有向图,问题抽象为拓扑排序。

    结果比较多,所以跑出来的测试数据和给的结果不一样,不过这个正常,也AC了。

    AC代码:

    #include <iostream>
    #include <cstdio>
    #include <cstdlib>
    #include <cctype>
    #include <cstring>
    #include <string>
    #include <sstream>
    #include <vector>
    #include <set>
    #include <map>
    #include <algorithm>
    #include <stack>
    #include <queue>
    #include <bitset> 
    #include <cassert> 
    
    using namespace std;
    
    const int maxn = 1000;
    int n, m, G[maxn][maxn], c[maxn], topo[maxn], t;
    
    bool dfs(int u) {
    	c[u] = -1; // 等于-1表示正在访问
    	for (int v = 0; v < n; v++) {
    		if (G[u][v]) {
    			if (c[v] < 0) { // 存在有向环,失败
    				return false;
    			}
    			else if (!c[v]) {
    				dfs(v);
    			}
    		}
    	}
    	c[u] = 1;
    	topo[--t] = u;
    	return true;
    }
    
    bool toposort()
    {
    	t = n;
    	memset(c, 0, sizeof(c));
    	for (int u = 0; u < n; u++) {
    		if (!c[u]) {
    			if (!dfs(u)) {
    				return false;
    			}
    		}
    	}
    	return true;
    }
    
    int main()
    {
    	while (scanf("%d", &n)&& n) {
    		scanf("%d", &m);
    		memset(G, 0, sizeof(G));
    		for (int i = 0; i < m; i++) {
    			int u, v;
    			scanf("%d%d", &u, &v);
    			u--;
    			v--;
    			G[u][v] = 1;
    		}
    		if (toposort()) {
    			for (int i = 0; i < n - 1; i++) {
    				printf("%d ", topo[i] + 1);
    			}
    			printf("%d
    ", topo[n - 1] + 1);
    		}
    		else {
    			printf("No
    ");
    		}
    	}
    
    	return 0;
    }



  • 相关阅读:
    Qual IPE中的Crop计算
    TinyCC安装
    C编译器(TCC)
    Macros之PRId64
    shell脚本学习 (10) 从结构化文本提取数据
    shell脚本学习 (9) 提取开头或结尾的几行
    shell脚本学习 (8) fmt 格式化段落
    接触python的第2天:了解变量和打印
    接触python的第1天:测试hello world
    shell脚本学习(7)sort
  • 原文地址:https://www.cnblogs.com/zhangyaoqi/p/4591556.html
Copyright © 2011-2022 走看看