codeforce 14D 无向图题目

http://vjudge.net/contest/view.action?cid=47975#problem/D

Description

As you know, Bob's brother lives in Flatland. In Flatland there are n cities, connected by n - 1 two-way roads. The cities are numbered from 1 to n. You can get from one city to another moving along the roads.

The «Two Paths» company, where Bob's brother works, has won a tender to repair two paths in Flatland. A path is a sequence of different cities, connected sequentially by roads. The company is allowed to choose by itself the paths to repair. The only condition they have to meet is that the two paths shouldn't cross (i.e. shouldn't have common cities).

It is known that the profit, the «Two Paths» company will get, equals the product of the lengths of the two paths. Let's consider the length of each road equals 1, and the length of a path equals the amount of roads in it. Find the maximum possible profit for the company.

Input

The first line contains an integer n (2 ≤ n ≤ 200), where n is the amount of cities in the country. The following n - 1 lines contain the information about the roads. Each line contains a pair of numbers of the cities, connected by the road ai, bi (1 ≤ ai, bi ≤ n).

Output

Output the maximum possible profit.

Sample Input

Input
4
1 2
2 3
3 4
Output
1
Input
7
1 2
1 3
1 4
1 5
1 6
1 7
Output
0
Input
6
1 2
2 3
2 4
5 4
6 4
Output
4
给定一个无向图,含有一定的路。从中找出两个最长的路径(每条路径有一些相通路组成)这两个路径不能经过公共的点,求何时二路径的乘积最大。

解题思路:枚举各个边将该边删除,然后取去掉这条边。分别找出分开两部分的最长的一条路径,求乘积即可。

值得注意的是:在输入的时候给出的是n-1条边,连接n个点,这种情况下是不可能存在环的,所以在写代码的时候根本就不用考虑环的问题。

#include <stdio.h>
#include <iostream>
#include <vector>
using namespace std;
vector <int> a[205];
int s;//全局
int dfs(int v,int x)
{
    int max1=0;
    int max2=0;
    int sum=0;
    for(int i=0;i<a[v].size();i++)
    {
        if(a[v][i]!=x)
        {
             sum=max(sum,dfs(a[v][i],v));
             if(s>max1)//max1保存的是从v出发长度最大的路,max2是从v出发次大的路(二者之和就是最长可扩展的路的长度)
             {
                 max2=max1;
                 max1=s;
             }
             else
                max2=max(max2,s);
        }
    }
    sum=max(sum,max1+max2);
    s=max1+1;
    return sum;
}
int main()
{
    int x,y,n;
    while(~scanf("%d",&n))
    {
        int maxx=0;
        for(int i=1;i<=n;i++)
              a[i].clear();
        for(int i=0;i<n-1;i++)
        {
            scanf("%d%d",&x,&y);
            a[x].push_back(y);
            a[y].push_back(x);
        }
        for(int i=1;i<=n;i++)
            for(int j=0;j<a[i].size();j++)
            {
                  //s=0;
                  x=dfs(i,a[i][j]);
                  y=dfs(a[i][j],i);
                  if(x*y>maxx)
                    maxx=x*y;
            }
        printf("%d\n",maxx);
    }
    return 0;
}


你可能感兴趣的:(codeforce 14D 无向图题目)