zoukankan      html  css  js  c++  java
  • POJ-3687 Labeling Balls(拓扑)

    不一样的拓扑排序 
    给定一些标记为1到n的数, 求出满足a < b 的序列, 如果有多个输出, 按先标签1往前的位置, 然后按标签2往前的位置, 对于每个标签, 位置都尽量往前。 
    因为位置要往前,就不能正向建图, 因为正向的拓扑每次在最前的都是最小的点, 并不能保证标签1也在最前面, 比如 
    1 5 3 4 2 
    和 
    1 4 5 3 2 
    如果按拓扑排序, 答案一定是1 4 5 3 2, 因为4比5小, 但是题目想要各个标签的位置往前, 这样1, 2标签位置一样, 对于3标签, 第一个在3处, 第二个在4处, 所以答案应该是上面那个。 
    所以正向建图是标签尽量往前,所以就反向建图得到 
    2 4 3 5 1 
    和 
    2 3 5 4 1 
    用less 的优先队列, 这样每次都把最大的放在后面, 就把小的留在前面了, 对于每一个标签, 都尽可能往后扔,最后在倒叙输出, 就可以得到答案。 
    题目还有一个点, 要求输出不是排序以后的各个标签的顺序, 而是在从1-n位置上的标签。 
    所以在倒叙的时候需要 ans[t] = num–; 

    #include<map>
    #include<queue>
    #include<string>
    #include<vector>
    #include<math.h>
    #include<ctype.h>
    #include<stdio.h>
    #include<string.h>
    #include<iostream>
    #include<algorithm>
    #define inf 0x3f3f3f3f
    
    typedef long long int ll;
    using namespace std;
    
    const int maxn = 205;
    
    int n, m;
    int ans[maxn];
    int ind[maxn];
    bool maps[maxn][maxn];
    
    void init() {
        memset(ans, 0, sizeof ans);
        memset(ind, 0, sizeof ind);
        memset(maps, 0, sizeof maps);
    }
    
    bool topu() {
        int num = n;
        priority_queue<int, vector<int>, less<int> > pq;
        for(int i=1; i<=n; i++) {
            if(ind[i] == 0) {
                pq.push(i);
            }
        }
        while(!pq.empty()) {
            int t = pq.top();
            pq.pop();
            ans[t] = num--;
            for(int i=1; i<=n; i++) {
                if(maps[t][i] == true) {
                    ind[i]--;
                    if(ind[i] == 0)
                        pq.push(i);
                }
            }
        }
        if(num == 0)
            return true;
        else
            return false;
    }
    
    int main() {
        int T;
        scanf("%d", &T);
        while(T--) {
            init();
            scanf("%d%d", &n, &m);
            for(int i=0; i<m; i++) {
                int u, v;
                scanf("%d%d", &u, &v);
                if(!maps[v][u]) {
                    maps[v][u] = true;
                    ind[u] ++;
                }
            }
            bool bo = topu();
            if(bo) {
                for(int i=1; i<=n; i++) {
                    printf("%d%c", ans[i], i==n ? '
    ' : ' ');
                }
            } else {
                printf("-1
    ");
            }
        }
        return 0;
    }
    View Code
  • 相关阅读:
    编写可维护的JavaScript代码(部分)
    Canvas
    初识ES6
    vue.js入门上
    ASP.NET中的物理路径与虚拟路径
    慎用标签选择器
    PHP服务器负载判断
    mac下安装redis
    mac安装memcache
    MySQL定时检查是否宕机并邮件通知
  • 原文地址:https://www.cnblogs.com/Jiaaaaaaaqi/p/9148295.html
Copyright © 2011-2022 走看看