poj 1985 Cow Marathon

@(K ACMer)

题意:
求树的最长路径
分析:
两次dfs求树的直径,无它.

#include <iostream>
#include <cstdio>
#include <cstring>
#include <set>
#include <map>
#include <stack>
#include <vector>
#include <string>
#include <queue>
#include <cstdlib>
#include <cmath>
#include <algorithm>
using namespace std;
typedef pair<int, int> pii;
typedef long long ll;
typedef vector<int> vi;
#define xx first
#define yy second
const int mod = int(1e9) + 7, INF = 0x3fffffff, maxn = 1e5 + 40;
vector<pii> v[maxn];
int n, m, l, s;

void dfs(int x, int y, int pre) {
    if (y > l) s = x, l = y;
    for (int i = 0; i < v[x].size(); i++) {
        if (v[x][i].xx == pre) continue;
        dfs(v[x][i].xx, y + v[x][i].yy, x);
    }
    return;
}


int main(void) {
    while (~scanf("%d%d", &n, &m)) {
        while (m--) {
            int x, y, z;
            scanf("%d%d%d %*c", &x, &y, &z);
            v[x].push_back(make_pair(y, z));
            v[y].push_back(make_pair(x, z));
        }
        l = 0;
        dfs(1, 0, -1);
        l = 0;
        dfs(s, 0, -1);
        printf("%d\n", l);
    }
    return 0;
}

你可能感兴趣的:(poj,DFS)