码迷,mamicode.com
首页 > 编程语言 > 详细

SGU 230. Weighings (拓扑排序)

时间:2015-05-17 21:28:35      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:

题意:

      给出质量为1~n的n个箱子的m对轻重关系,输出一种可能的箱子的质量排列。

 

 


Solution:

     拓扑排序,注意要处理重边。

技术分享
#include <iostream>
#include <queue>
using namespace std;

const int N = 209;

queue<int> q;
bool G[N][N];
int deg[N], ans[N];
int n, m;

int main()
{
    ios::sync_with_stdio (0);
    cin >> n >> m;
    for (int i = 1, u, v; i <= m; ++i) {
        cin >> u >> v;
        if(!G[u][v]){
            G[u][v]=1;
            deg[v]++;
        }
    }
    for (int i = 1; i <= n; i++) {
        if (deg[i]==0) q.push (i);
    }
    int now = 0;
    while (!q.empty() ) {
        int u = q.front(); q.pop();
        ans[u] = ++now;
        for (int i = 1; i <= n; i++) {
            if (G[u][i] && (--deg[i]) == 0) {
                q.push (i);
            }
        }
    }
    if (now == n) {
        for (int i = 1; i <= n; i++)
            cout << ans[i] <<  ;
    }
    else {
        cout << "No solution\n";
    }
    return 0;
}
View Code

 

SGU 230. Weighings (拓扑排序)

标签:

原文地址:http://www.cnblogs.com/keam37/p/4510317.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!