superlevin 2022-05-12 20:58 采纳率: 100%
浏览 58
已结题

DAG演算法透過C++實踐

Here is a Directed Acyclic Graph (DAG) with weight on nodes.

If there is a directed path from node to node , node is a successor of node . itself is defined as one of the successors of as well.
Please calculate the maximal weight among weights of all successors of for each in the DAG.

The first line is n,m , which are number of nodes and directed edges in the DAG.
The following n line are n integers representing weight of node , i0≤i<.
The following m line after weights are m pair of integers(a,b) , which represents directed edge from a to b .
Constraints
0<n<=10000
0<m<=50000
0<wieght<=10000
0<=a,b<n
Output Format
Print n integers in a line separate with a space.

The i-th integer is the answer corresponding to node i 0<=i<n
Sample Input
4 4
1 4 3 2
0 1
1 2
1 3
3 2
Sample Output
4 4 3 3
Sample Input
5 5
1 4 3 2 8
0 1
1 2
1 3
3 2
0 4
Sample Output
8 4 3 3 8

請問如何解?


#include <cstdio> 
#include <vector> 
#include <iostream>
 #include <algorithm> 
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */ 
return 0;
}
  • 写回答

1条回答 默认 最新

  • 丨秋水丨 2022-05-12 21:54
    关注

    img

    #include <cstdio> 
    #include <vector> 
    #include <iostream>
    #include <algorithm> 
    using namespace std;
    struct Node
    {
        int weight;
        std::vector<int> successors;
    };
    int main() {
        int n, m;
        cin >> n >> m;
        std::vector<Node> nodes;
        nodes.resize(n);
        for (int i = 0; i < n; ++i)
        {
            int w;
            cin >> w;
            nodes[i].weight = w;
        }
        for (int i = 0; i < m; ++i)
        {
            int l, r;
            cin >> l >> r;
            nodes[l].successors.push_back(r);
        }
        for (int i = 0; i < n; ++i)
        {
            int maxWeight = nodes[i].weight;
            for (int j = 0; j < nodes[i].successors.size(); ++j)
            {
                if (maxWeight < nodes[nodes[i].successors[j]].weight)
                {
                    maxWeight = nodes[nodes[i].successors[j]].weight;
                }
            }
            cout << maxWeight;
            if (i != n - 1)cout << " ";
        }
        return 0;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 5月13日
  • 已采纳回答 5月12日
  • 赞助了问题酬金60元 5月12日
  • 创建了问题 5月12日

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化