1.问题内容:
2.问题分析:
深入分析,就会知道此题考查的是图论基本算法-拓扑排序。关于拓扑排序算法的伪代码如下:
L← Empty list that will contain the sorted elements
S ← Set of all nodes with no incoming edges
while S is non-empty do
remove a node n from S
insert n into L
for each node m with an edge e from n to m do
remove edge e from the graph
if m has no other incoming edges then
insert m into S
if graph has edges then
return error (graph has at least one cycle)
else
return L (a topologically sorted order)
3.解题思路:
首先根据题目的数据构造图的数据结构(这里采用的是链表实现,具体信息请参见-图的表示方法)
然后进行拓扑排序并且确定最少奖金的求解逻辑,这里首先初始化出度为0的节点reward值为100,然后在队列非空的条件下,对不同节点的reward值进行计算,核心为:reward[*it] = reward[front] + 1;(即当前节点的reward值为前驱的reward值加一)。
4.参考代码:
/*分类:图论算法,拓扑排序*/
#include<iostream>
#include<cstring>
#include<list>
#include<queue>
using namespace std;
int main() {
int faculty, repre;
cin >> faculty >> repre;
list<int> graph[faculty + 1]; //使用链表来记录图的信息。
queue<int> queue;//处理队列。
int ingoing[faculty + 1]; //记录每个节点的出度。
int reward[faculty + 1]; //记录每个人的奖金额
int count = 0;//已进行拓扑排序的节点个数。
int from, to;
memset(ingoing, 0, sizeof(ingoing));//初始化每个节点的入度为0
for (int i = 1; i <= repre; i++) {//图的边和阶段信息初始化。
cin >> from >> to;
graph[to].push_back(from);
ingoing[from]++;
}
for (int i = 1; i <= faculty; i++) {//将入度为0的节点接入到队列中。
if (ingoing[i] == 0) {
queue.push(i);
reward[i] = 100;
}
}
while(!queue.empty()) {//处理每个经评价的边。
int front = queue.front();
queue.pop();
count++;
//拓扑排序核心。
for (list<int>::iterator it = graph[front].begin(); it != graph[front].end(); ++it) {
if (--ingoing[*it] == 0) {
queue.push(*it);
}
reward[*it] = reward[front] + 1;
}
}
if (count == faculty) {
int sum = 0;
for (int i = 1; i <= faculty; i++) sum += reward[i];
cout << sum << endl;
} else {//存在环路。
cout << "Poor Xed\n";
}
}