1985. Cow Marathon

 

After hearing about the epidemic of obesity in the USA, Farmer John wants his cows to get more exercise, so he has committed to create a bovine marathon for his cows to run. The marathon route will include a pair of farms and a path comprised of a sequence of roads between them. Since FJ wants the cows to get as much exercise as possible he wants to find the two farms on his map that are the farthest apart from each other (distance being measured in terms of total length of road on the path between the two farms). Help him determine the distances between this farthest pair of farms.

 

Input. The first line contains number of farms n and number of roads m. Each of the next m lines contains four space-separated entities: f1, f2, l and d that describe a road. f1 and f2 are numbers of two farms connected by a road, l is its length, and d is a character that is either 'N', 'E', 'S', or 'W' giving the direction of the road from f1 to f2.

 

Output. Print an integer giving the distance between the farthest pair of farms.

 

Sample Input

7 6

1 6 13 E

6 3 9 E

3 5 7 S

4 1 3 N

2 4 20 W

4 7 2 S

 

Sample Output

52

 

 

РЕШЕНИЕ

деревья

 

Анализ алгоритма

В заданном взвешенном дереве следует найти диаметр. Граф храним в виде списка смежности. Направления дорог несущественны.

 

Реализация алгоритма

 

#include <cstdio>

#include <vector>

#include <algorithm>

using namespace std;

 

struct Node

{

  int to;

  int len;

  Node(int to, int len) : to(to), len(len) {};

};

vector<vector<Node> > g;

int diameter, i, n, m, u, v, d;

char s[100];

 

int dfs(int v, int prev = -1)

{

  int h1 = 0, h2 = 0; // highest and second highest height

  for(int i = 0; i < g[v].size(); i++)

  {

    int to = g[v][i].to;

    int len = g[v][i].len;

    if (to != prev)

    {

      int h = dfs(to,v) + len;

      if (h > h1) h2 = h1, h1 = h;

        else if (h > h2) h2 = h;

    }

    diameter = max(diameter, h1 + h2);

  }

  return h1;

}

 

int main(void)

{

  scanf("%d %d",&n,&m);

  g.resize(n+1);

  for(i = 0; i < m; i++)

  {

    scanf("%d %d %d",&u,&v,&d); gets(s);

    g[u].push_back(Node(v,d));

    g[v].push_back(Node(u,d));

  }

 

  diameter = 0;

  dfs(1);

  printf("%d\n",diameter);

  return 0;

}