1424.奖金(拓扑排序)
来源:互联网 发布:驾驶员疲劳检测软件 编辑:程序博客网 时间:2024/05/22 04:59
/*1424.奖金(拓扑排序) 给出系列数对,如a b 则要求a的奖金比b高。求出满足所有要求的 最少奖金和 思路:把奖金少的排在前面,则如a b有b->a的连线...依次建立有向图 然后统计各个点的入度,然后把入度为0的先入队,进行拓扑排序 取得队列头,然后遍历其下行节点,相应的入度-1,如果入度变为0 则入队,然后使其对应的奖金在当前节点基础上+1 最后,队列空退出。判断排好序的个数sorted,如果sorted == n则 说明无环,否则有环 */#include <iostream>#include <stdlib.h>#include <memory.h>#include <vector>#include <queue>using namespace std;vector<int> node[10004];int inDegree[10004];int n, m;int bonus[10004];int main(){ int a, b; queue<int> q; while (cin >> n >> m) { memset(inDegree, 0, sizeof(inDegree)); memset(bonus, 0,sizeof(bonus)); for (int i = 1; i <= m; i ++) { cin >> a >> b; node[b].push_back(a); inDegree[a] ++; } //入度为0的点先进入队列,并将其奖金初始化为100 for (int i = 1; i <= n; i ++){ if (inDegree[i] == 0) { q.push(i); bonus[i] = 100; } } int sum = 0, sorted = 0, t; //遍历队列 while ( !q.empty()) { t = q.front(); sum += bonus[t]; q.pop(); //记录已经排序的个数 sorted++; for (int i = 0; i < node[t].size(); i++) { inDegree[node[t][i]] --; //如果当前的t点的下行点入度为0,则入队 if (inDegree[node[t][i]] == 0) q.push(node[t][i]); //下行点的奖金比当前t多1 bonus[node[t][i]] = bonus[t] +1; } } //如果不能实现排好序的个数==n,则说明有环 if(sorted == n) cout << sum << endl; else cout << "Poor Xed" << endl; } system("pause"); return 0;}