sicily 1424. 奖金

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值