Lightoj 1094 DFS

10 篇文章 0 订阅

DFS 搜索下经过每个点的最大长度就行。。。。

AC代码如下:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

typedef struct{
	int to;
	int weight;
	int next;
}Edge;

int head[40010], tot;
Edge edge[70010];
int N;
int max_distance;

void add_edge( int a, int b, int weight ){
	edge[tot].to = b;
	edge[tot].weight = weight;
	edge[tot].next = head[a];
	head[a] = tot++;
	edge[tot].to = a;
	edge[tot].weight = weight;
	edge[tot].next = head[b];
	head[b] = tot++;
}

int DFS( int pos, int pre ){
	int first_max, second_max;
	first_max = second_max = 0;
	
	for( int i = head[pos]; i != -1; i = edge[i].next ){
		int to = edge[i].to;
		if( to == pre ){
			continue;
		}
		int temp_dis = edge[i].weight + DFS( to, pos );
		if( temp_dis > first_max ){//注意要更新这个second_max!!!
			second_max = first_max;
			first_max  = temp_dis;
		}else if( temp_dis > second_max ){
			second_max = temp_dis;
		}
	}

	if( first_max + second_max > max_distance ){
		max_distance = first_max + second_max;
	}

	return first_max;
}

int main(){
	int T, Case = 1;
	
	scanf( "%d", &T );
	while( T-- ){

		memset( head, -1, sizeof( head ) );
		tot = 0;

		scanf( "%d", &N );
		int temp1, temp2, temp3;
		for( int i = 1; i < N; i++ ){
			scanf( "%d%d%d", &temp1, &temp2, &temp3 );
			add_edge( temp1, temp2, temp3 );
		}

		max_distance = 0;

		DFS( 0, -1 );

		cout << "Case " << Case++ << ": " << max_distance << endl;
	}
	return 0;
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值