uva 10308 - Roads in the North(dfs)

737 篇文章 0 订阅
223 篇文章 1 订阅

题目链接:uva 10308 - Roads in the North


题目大意:给出一个无环无向图,求任意两点间的最大距离。输入空行问该组测试输入结束。


解题思路:输入比较恶心,因为这个WA了一次,这题可以用dfs去做,任意选一个节点作为根节点,然后遍历与它相连的所有点,维护最大值就可以了,因为任意两点可以看成是以父亲节点而相连的。


#include <stdio.h>
#include <string.h>
#include <vector>
#define max(a,b) (a)>(b)?(a):(b)
using namespace std;
const int N = 10005;
const int INF = (1 << 31) - 1;

struct State {
	int id;
	int val;
	State (int x = 0, int c = 0) {
		id = x, val = c;
	}	
};

vector<State> v[N];
int ans, rec[N];

void init() {
	ans = 0;
	for (int i = 0; i < N; i++)
		v[i].clear();
	memset(rec, 0, sizeof(rec));
}

void add(int x, int y, int value) {
	State c(y, value);
	v[x].push_back(c);
}

int dfs(int x) {
	int Max = 0;
	int n = v[x].size();

	rec[x] = 1;
	for (int i = 0; i < n; i++) {
		if (rec[v[x][i].id]) continue;
		int c = dfs(v[x][i].id) + v[x][i].val;

		ans = max(Max + c, ans);
		Max = max(Max, c);
	}
	rec[x] = 0;
	return Max;
}

int main () {
	int a, b, value;
	char str[100];
	while (gets(str)) {
		init();
		while (str[0] != '\0') {
			sscanf(str, "%d%d%d", &a, &b, &value);
			add(a, b, value);
			add(b, a, value);
			if (!gets(str)) break;
		}

		dfs(1);
		printf("%d\n", ans);
	}
	return 0;
}


  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值