CF14D Two Paths(树的直径)

// Problem: CF14D Two Paths
// Contest: Luogu
// URL: https://www.luogu.com.cn/problem/CF14D
// Memory Limit: 62.5 MB
// Time Limit: 2000 ms
// Author:Cutele
// 
// Powered by CP Editor (https://cpeditor.org)


#pragma GCC optimize(1)
#pragma GCC optimize(2)
#pragma GCC optimize(3,"Ofast","inline")
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<ll, ll>PLL;
typedef pair<int, int>PII;
typedef pair<double, double>PDD;
#define I_int ll
inline ll read()
{
    ll x = 0, f = 1;
    char ch = getchar();
    while(ch < '0' || ch > '9')
    {
        if(ch == '-')f = -1;
        ch = getchar();
    }
    while(ch >= '0' && ch <= '9')
    {
        x = x * 10 + ch - '0';
        ch = getchar();
    }
    return x * f;
}

inline void out(ll x){
    if (x < 0) x = ~x + 1, putchar('-');
    if (x > 9) out(x / 10);
    putchar(x % 10 + '0');
}

inline void write(ll x){
    if (x < 0) x = ~x + 1, putchar('-');
    if (x > 9) write(x / 10);
    putchar(x % 10 + '0');
}

#define read read()
#define closeSync ios::sync_with_stdio(0);cin.tie(0);cout.tie(0)
#define multiCase int T;cin>>T;for(int t=1;t<=T;t++)
#define rep(i,a,b) for(int i=(a);i<=(b);i++)
#define repp(i,a,b) for(int i=(a);i<(b);i++)
#define per(i,a,b) for(int i=(a);i>=(b);i--)
#define perr(i,a,b) for(int i=(a);i>(b);i--)
ll ksm(ll a, ll b)
{
    ll res = 1;
    while(b)
    {
        if(b & 1)res = res * a ;
        a = a * a ;
        b >>= 1;
    }
    return res;
}
const int maxn=210;
vector<int>g[maxn];
int n,maxl=0;

int dfs(int u,int fa){
	int l1=0,l2=0,res=0;
	for(int i=0;i<g[u].size();i++){
		int j=g[u][i];
		if(j==fa) continue;
		res=max(res,dfs(j,u));
		if(maxl>l1){
			l2=l1,l1=maxl;
		}
		else{
			l2=max(maxl,l2);
		}
	}
	res=max(res,l1+l2);
	maxl=l1+1;
	return res;
}

int main(){
	n=read;
	rep(i,1,n-1){
		int u=read,v=read;
		g[u].push_back(v);
		g[v].push_back(u);
	}
	int res=0;
	for(int i=1;i<=n;i++){
		for(int j=0;j<g[i].size();j++){
			int d1=dfs(g[i][j],i),d2=dfs(i,g[i][j]);
			res=max(res,d1*d2);
		}
	}
	write(res);
	return 0;
}
原文地址:https://www.cnblogs.com/OvOq/p/15101765.html