C++程序找出最小连通图的最大和
假设我们给定一个最小连通图。这意味着移除任何一条边都会使图断开连接。该图有n个顶点,边在数组'edges'中给出。还有一个数组'vertexValues'包含n个整数值。
现在,我们执行以下操作:
我们在每个顶点上写一个正整数,然后尝试计算分数。
如果连接两个顶点的边存在,我们将两个顶点中较小的值放在边上。
我们通过将所有边值相加来计算分数。
我们必须找到通过在顶点上放置值可以达到的最大值。我们必须打印最大总值以及要写在顶点上的值。
因此,如果输入类似于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 < n, update (increase i by 1), do:
tmp := first value of edges[i]- 1
temp := second value of edges[i] - 1
insert temp at the end of tp[tmp]
insert tmp at the end of tp[temp]
for initialize i := 0, when i < n, update (increase i by 1), do:
seq[i] := vertexValues[i]
c := n - 1
sort the array seq
dfs(0, 0)
print(ans)
for initialize i := n - 1, when i >= 0, update (decrease i by 1), do:
print(res[i])示例
让我们看看下面的实现以更好地理解:
#include <bits/stdc++.h>
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<int,int>> edges, int vertexValues[]){
for(int i = 0; i + 1 < n; i++) {
int tmp = edges[i].first - 1;
int temp = edges[i].second - 1;
tp[tmp].push_back(temp);
tp[temp].push_back(tmp);
}
for(int i = 0; i < n; i++)
seq[i] = vertexValues[i];
c = n - 1;
sort(seq, seq + n);
dfs(0, 0);
cout << ans << endl;
for(int i = n - 1; i >= 0; i--)
cout << res[i] << " ";
cout << endl;
}
int main() {
int n = 6;
vector<pair<int,int>> 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;
}输入
6, {{1, 2}, {2, 3}, {2, 4}, {4, 5}, {3, 6}}, {1, 2, 3, 4, 5, 6}
输出
15 3 1 2 4 5 6
广告
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP