
假设我们有一个最小连通图。这意味着删除任何边都会使图断开连接。该图有 n 个顶点,边在数组“edges”中给出。我们还获得了一个包含 n 个整数值的数组“vertexValues”。
现在,我们执行以下操作 -
我们在每个顶点上写一个正整数,然后尝试计算一个分数。
有一条边连接两个顶点,我们将两个顶点中较小的值放在边缘。
-
我们通过添加所有边缘值来计算分数。
我们必须找到最大值可以通过将值放在顶点上来实现。我们必须打印最大总值以及要写入顶点的值。
因此,如果输入类似于 n = 6,则 Edges = {{1, 2}, {2, 3} , {2, 4}, {4, 5}, {3, 6}}, vertexValues = {1, 2, 3, 4, 5, 6},则输出将为 15, 3 1 2 4 5 6,因为我们可以按照给定的方式 3 1 2 4 5 6 将值放在从 0 到 n – 1 的顶点上。
为了解决这个问题,我们将遵循以下步骤 -
N := 100
Define arrays seq and res of size N.
Define an array tp of size N.
ans := 0
Define a function dfs(), this will take p, q,
res[p] := seq[c]
if p is not equal to 0, then:
ans := ans + seq[c]
(decrease c by 1)
for each value x in tp[p], do:
if x is not equal to q, then:
dfs(x, p)
for initialize i := 0, when i + 1 = 0, update (decrease i by 1), do:
print(res[i])
示例
让我们看看以下实现,以便更好地理解 -
#include <bits>
using namespace std;
const int INF = 1e9;
#define N 100
int seq[N], res[N];
vector<int> tp[N];
int ans = 0, c;
void dfs(int p, int q) {
res[p] = seq[c];
if(p != 0)
ans += seq[c];
c--;
for(auto x : tp[p]) {
if(x != q)
dfs(x, p);
}
}
void solve(int n, vector<pair>> edges, int vertexValues[]){
for(int i = 0; i + 1 = 0; i--)
cout > edges = {{1, 2}, {2, 3}, {2, 4}, {4, 5},{3, 6}};
int vertexValues[] = {1, 2, 3, 4, 5, 6};
solve(n, edges, vertexValues);
return 0;
}</pair></int></bits>
输入
6, {{1, 2}, {2, 3}, {2, 4}, {4, 5}, {3, 6}}, {1, 2, 3, 4, 5, 6}
输出
15 3 1 2 4 5 6
C++免费学习笔记(深入):立即使用
在学习笔记中,你将探索 C++ 的入门与实战技巧!











