时间限制:20000ms 单点时限:1000ms 内存限制:256MB 描述 幻想乡有一个赛车场。赛车场里有N个地点。同时地点之间还有单向的道路存在。 这些道路使得赛车场形成了一个外向树的结构。也就是说,道路将这N个地点连成了一个有根树。并且所有的边都是从父亲指向孩子的。 由于幽香喜欢刺激,每次她去赛车场都会从根节点出发,选择最长的一条路径来玩。 但是现在幽香感觉最长的路径还是太短了,她打算在赛车场里新建一条道路使得新的最长路径最长。 同时,如果道路形成了一个环,那么可能会出现交通事故,所以幽香新建的道路不能导致环的出现。 你能帮幽香算出新建一条道路后的最长路径吗?幽香知道根节点一定是1号点。 输入 一行一个数N,表示地点的数量。 接下来N-1行,每行两个数a和b,表示从点a到点b有一条单向路径。所有点从1到n标号。 数据范围: n<=100000。 输出 一行表示新建一条边后的最长路径。 样例输入 5 1 2 2 3 1 4 4 5 样例输出 4
树形dp,统计节点的最大子树深度和次大子树深度和,最大的即为结果
#pragma comment(linker,"/STACK:102400000,102400000")
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <iomanip>
#include <cmath>
#include <algorithm>
#include <stack>
#include <queue>
#include <map>
#include <fstream>
using namespace std;
typedef long long ll;
const int INF = 0x3f3f3f3f;
const int MAX = 0x7fffffff;
const ll LINF = 0x3f3f3f3f3f3f3f3f;
const ll LMAX = 0x7fffffffffffffff;
const double pi=acos(-1.0);
const int maxn = 100000+5;
const int maxm = 100000+5;
const int mod = 1000000007;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
vector<int> v[maxn];
void init(int n)
{
for(int i=1; i<=n; ++i)
v[i].clear();
}
int ans;
int max_f[maxn][2];
void dfs(int root,int cnt)
{
bool yezi=true;
for(int i=0; i<v[root].size(); ++i)
{
int next=v[root][i];
yezi=false;
dfs(next,cnt+1);
if(max_f[root][1]<max_f[next][1]+1)
{
max_f[root][0]=max_f[root][1];
max_f[root][1]=max_f[next][1]+1;
}
else if(max_f[root][0]<max_f[next][1]+1)
{
max_f[root][0]=max_f[next][1]+1;
}
}
if(yezi)
{
max_f[root][1]=max_f[root][1]=0;
}
else
{
ans=max(ans,cnt+max_f[root][1]+max_f[root][0]);
}
}
int main()
{
//freopen("input.txt","r",stdin);
//freopen("output.txt","w",stdout);
int n;
while(cin>>n)
{
init(n);
int a,b;
for(int i=1; i<n; ++i)
{
scanf("%d %d",&a,&b);
v[a].push_back(b);
}
memset(max_f,0,sizeof max_f);
ans=0;
dfs(1,0);
printf("%d\n",ans);
}
return 0;
}
1A继续努力
原文:http://www.cnblogs.com/glb666/p/4779371.html