八中友好教室2

题目

前置题目

八中友好教室1-CSDN博客

思路

这一题与八中友好教室1差不多,但是题目把"最小"改成了"最大"。

那么很简单,我们只要将每一条边都连一次就行了。

代码

cpp 复制代码
#include<bits/stdc++.h>
#define int long long
using namespace std;
struct node
{
  int u,len;
};
vector<node>vec[1000001];
int ans,zi[1000001],n,x,y,len;
inline int read() {int x=0,f=1;char ch=getchar();while(ch<'0'||ch>'9') {if(ch=='-')f=-1;ch=getchar();}while(ch>='0'&&ch<='9') x=x*10+ch-'0',ch=getchar();return x*f;}
void dfs(int u,int fa)
{
  zi[u] = 1;
  for(int i = 0;i < vec[u].size();i++)
	if(vec[u][i].u != fa)
	{
	  dfs(vec[u][i].u,u);
	  zi[u] += zi[vec[u][i].u];
	  ans += vec[u][i].len * zi[vec[u][i].u];
	}
}
signed main()
{
  cin>>n;
  for(int i = 1;i < n;i++)
  {
	x = read();
    y = read();
    len = read();
	vec[x].push_back({y,len});
	vec[y].push_back({x,len});
  }
  dfs(1,0);
  cout<<ans<<endl;
  return 0;
}
相关推荐
白狐_7984 小时前
408数据结构第6章:图——核心考点、算法对比与AOE网真题
数据结构·算法
变量未定义~4 小时前
DFS之剪枝与优化-小猫爬山、 数独、 木棒
算法
Navigator_Z4 小时前
LeetCode //C - 1187. Make Array Strictly Increasing
c语言·算法·leetcode
龍德明宇5 小时前
如何理解大语言模型的负主体性-龍德明宇
人工智能·算法·大语言模型llm·负主体性·ai存在论
白狐_7985 小时前
408数据结构第6章:迪杰斯特拉(Dijkstra)算法——真题精讲
数据结构·算法
皓月斯语6 小时前
P2858 [USACO06FEB] Treats for the Cows G/S
数据结构·c++·算法·动态规划
旖旎夜光6 小时前
LeetCode 397:整数替换(贪心问题) —— 题解
数据结构·c++·算法·leetcode·贪心算法
奈斯先生Vector6 小时前
2026 开发者效能革命:基于创源AIGC 与开源生态的工程化实践、安全沙箱与代码智能体协同
人工智能·算法·架构·prompt·aigc
依然鸣6 小时前
PTA团体程序设计天梯赛L2真题讲解L2-037-040
c++·经验分享·学习·算法·蓝桥杯·深度优先·pat考试
Sagittarius_A*6 小时前
哈希与认证基础(一):哈希函数的安全目标:原像、第二原像与碰撞
算法·安全·信息安全·密码学·哈希算法