poj1985树的直径

点击打开链接

#include 
#include 
#include 
using namespace std;
const int maxn = 500000 + 10;
const int maxm = maxn + 10;
int head[maxn], pos, n, m, vis[maxn], dist[maxn];
struct edge
{
	int to;
	int next;
	int w;
}Edge[maxm];
void addEdge(int u, int v, int w){
	Edge[pos].to = v;
	Edge[pos].w = w;
	Edge[pos].next = head[u];
	head[u] = pos;
	pos++;
}
void init(){
	for(int i = 0; i < maxn; i++) head[i] = -1;
	pos = 0;
}
void dfs(int u, int d){
	vis[u] = 1;
	dist[u] = d;
	for(int k = head[u]; k != -1; k = Edge[k].next){
		int v = Edge[k].to;
		if(!vis[v]){
			dfs(v, Edge[k].w + d);
		}
	}
}
int getDiameter(){
	memset(vis, 0 , sizeof(vis));
	memset(dist, 0, sizeof(dist));
	dfs(1, 0); // 从任意一点开始进行dfs
	int u = -1, maximum = -1;
	for(int i = 1; i <= n; i++){
		if(dist[i] > maximum){
			maximum = dist[i]; // 找到距离最远的点u
			u = i;
		}
	}
	memset(vis, 0 , sizeof(vis));
	memset(dist, 0, sizeof(dist));
	dfs(u, 0); // 从u点开始进行dfs
	u = -1, maximum = -1;
	for(int i = 1; i <= n; i++){
		if(dist[i] > maximum){
			maximum = dist[i]; // 找到距离最远的点v,这个距离就是树的直径 
			u = i;
		}
	}
	return maximum;
}
int main(){
	//freopen("input.txt", "r", stdin);
	while(scanf("%d%d", &n, &m) != EOF){
		init();
		for(int i = 1; i <= m; i++){
			char temp;
			int u, v, w;
			scanf("%d%d%d", &u, &v, &w);
			getchar();
			getchar();
			//cout << u << v << w << endl;
			addEdge(u, v, w);
			addEdge(v, u, w);
		}
		int ans = getDiameter();
		printf("%d\n", ans);
	}
	return 0;
}

你可能感兴趣的:(图论)