和第一题题解思路一样,我的搜过不过,找不出问题所在
查看原帖
和第一题题解思路一样,我的搜过不过,找不出问题所在
520264
Clement_D_Alger楼主2024/6/12 18:03
#include<bits/stdc++.h>
#define NX 500005
using namespace std;

bool vis[NX], vv[NX];//标记 
long long val[NX], ans; //总深度 

struct node
{
	int to, w, Next;	
}E[NX*2];
int head[NX], cnt, n, t, x, y, v;
void add_edge(int u, int v, int w)
{
	cnt++;
	E[cnt].to = v;
	E[cnt].w = w;
	E[cnt].Next = head[u];
	head[u] = cnt;
}

void dfs(int x)
{
	for(int i = head[x]; i; i = E[i].Next)
	{
		int y = E[i].to, v = E[i].w;
		if(vis[y] == 0)//如果这个点没有搜过,那它是子节点 
		{
			vis[y] = 1;//标记搜过 
			dfs(y);//要先搜才会有数据 
			val[x] = max(val[x], v + val[y]);		
		}
	}
	//每个支点的最长度加到父节点的长度 与 其父节点最长度 之差 
	for(int i = head[x]; i; i = E[i].Next)
	{
		int y = E[i].to, v = E[i].w;
		if(vv[y] == 0)
		{
			vv[y] = 1;
			ans += val[x] - (val[y] + v);
		}
	}
	return;
}
int read();

int main()
{  
	n = read(), t = read();
	for(int i = 1; i < n; i++)
	{
		x = read(), y = read(), v = read();
		add_edge(x, y, v);
		add_edge(y, x, v); 
	}
	
	vis[t] = 1, vv[t] = 1;
	dfs(t);//从起点开始走 
	cout << ans << '\n';
	return 0;
}
int read()
{
	int x = 0;
	char c = getchar();
	while(c < '0' || c > '9')
	{
		c = getchar();
	}
	while(c >= '0' && c <= '9')
	{
		x = x * 10 + c - '0';
		c = getchar();
	}
	return x;
}
请问我的搜索为啥不对,我是百思不得其解
2024/6/12 18:03
加载中...