Exercise - Diameter of a tree

6: The diameter of the tree


Total time limit: 
1000ms
Memory limit: 
65536kB
describe

The "diameter" of a tree T is defined as the maximum distance between nodes. Given a weighted tree T, find the length of the diameter of T.

enter
The first line contains two integers N and M, indicating that there are N nodes and M undirected edges in the graph. (N <= 5000, M<n)
The next M lines, each line contains 3 integers {u, v, w}, indicating that there is an undirected edge connecting the nodes u, v
* The input is guaranteed to be an acyclic graph
output
an integer representing the diameter length
sample input
4 3
1 2 1
2 3 2
2 4 3
Sample output
5
hint
* The input graph is not necessarily connected, the question asks to find the diameter of the subtree where node 1 is located

Ideas:

1. Save the graph; 2. Because it is an acyclic graph and the diameter of the subtree where node 1 is located, the depth-first search starts from 1 to each node, and saves another node where the longest path is located ; 3. Taking this node as the starting point again, depth-first search is performed to obtain the diameter length.

but! ! ! It's wrong, what exactly is wrong, and then change it after listening to the class at night!

The error code is as follows:

#include <iostream>
#include <vector>
#include <cstring>
using namespace std;

struct node{
	int point;
	int value;
};

int _point=0;
int _diameter=0;
int *mark1;
int *mark2;
vector<node> relation[5002];

void dfs(int x, int start, int *mark)
{
	for(int i=0; i<(int)relation[x].size(); i++)
	{
		if(relation[x][i].point == start)//起点为0 
			continue;
		if(mark[relation[x][i].point] != 0)//是旧点 
			continue;
		mark[relation[x][i].point] = mark[x] + relation[x][i].value;
		if(mark[relation[x][i].point] > _diameter)
		{
			_diameter = mark[relation[x][i].point];
			_point=relation[x][i].point;
		}
		dfs(relation[x][i].point, start, mark);
	}
} 

int main(int argc, char *argv[]) {
	int N, M, u,v,w;
	node node_u, node_v;
	mark1 = new int[N+1]; memset(mark1,0,sizeof(mark1));
	mark2 = new int[N+1]; memset(mark2,0,sizeof(mark2));
	//relation = new vector<node>[N];
	cin>>N>>M;
	//建立关系图 
	for(int i=0; i<M; i++)
	{
		cin>>u>>v>>w;
		node_u.point = v; node_v.point = u;
		node_u.value = node_v.value = w; 
		relation[u].push_back(node_u);
		relation[v].push_back(node_v);
	}
	//找到直径的一个点 
	dfs(1 ,1,mark1);
	dfs(_point,_point,mark2);
	cout<<_diameter;
	
	return 0;
}










Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324672624&siteId=291194637