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



  • 相关阅读:
    VS2010 自动跳过代码现象
    Reverse Linked List II 【纠结逆序!!!】
    Intersection of Two Linked Lists
    Linked List Cycle II
    Remove Nth Node From End of List 【另一个技巧,指针的指针】
    Swap Nodes in Pairs
    Merge Two Sorted Lists
    Remove Duplicates from Sorted List
    Linked List Cycle
    Dungeon Game
  • 原文地址:https://www.cnblogs.com/zhangyaoqi/p/4591556.html
Copyright © 2011-2022 走看看