您的位置:首页 > 其它

Codeforces 14D Two Path Solution

2016-06-26 07:51 381 查看
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.

Solution

原题的数据范围好像很小,n3可以过?

比赛的时候标程是n2的?

然而我的做法是O(n)的==

关于直径的题我好像从来不用直径写,而是喜欢倍增或者树形dp

这题我就瞎逼树形dp的

先分类讨论一下乘积最大两条路径可能出现的位置。

然后dp就好啦

Code

#include<iostream>
#include<string.h>
#include<stdio.h>
#include<algorithm>
#include<vector>
using namespace std;
const int M=3005;
#define pb push_back
#define vec vector<int>
struct node{
int v,pos;
inline bool operator < (const node &tmp)const{
return v>tmp.v;
}
};
#define vecn vector<node>
typedef long long ll;
int ans;
inline void Max(int &a,int b){if(a<b)a=b;}
vec G[M];
int dp[M],d[M],md[M],n;
//dp:伞状路径最大值
//d:最深子孙深度
vecn stu;
inline void predfs(int v,int f,int dep){
md[v]=d[v]=dep;
for(int i=0;i<G[v].size();++i)
if(G[v][i]^f)predfs(G[v][i],v,dep+1);
for(int i=0;i<G[v].size();++i)
if(G[v][i]^f)Max(md[v],md[G[v][i]]);
}
inline void dfs(int v,int f,int Mxlen){
int k1=Mxlen,k2=Mxlen,p1=-1,p2=-1;
for(int i=0;i<G[v].size();++i){
if(G[v][i]==f)continue;
if(md[G[v][i]]-d[v]>k1){
swap(k1,k2),swap(p1,p2);
k1=md[G[v][i]]-d[v],p1=i;
}
else if(md[G[v][i]]-d[v]>k2)k2=md[G[v][i]]-d[v],p2=i;
}
for(int i=0;i<G[v].size();++i)
if(G[v][i]^f){
if(i==p1)dfs(G[v][i],v,k2+1);
else dfs(G[v][i],v,k1+1);
}
for(int i=0;i<G[v].size();++i)
if(G[v][i]^f)stu.pb((node){md[G[v][i]]-d[v],i});
sort(stu.begin(),stu.end());
for(int i=0;i<G[v].size();++i){//枚举一个dp val
if(G[v][i]==f)continue;
int tmp=0,cnt=0;
for(int j=0;j<stu.size();++j){
if(stu[j].pos==i)continue;
Max(ans,1ll*dp[G[v][i]]*(stu[j].v+Mxlen));//卜型  如样例3
++cnt,tmp+=stu[j].v;
if(cnt==2)break;
}
Max(ans,1ll*dp[G[v][i]]*tmp);//伞型
Max(ans,1ll*dp[G[v][i]]*Mxlen);
}
dp[v]=0;
for(int i=0;i<2&&i<stu.size();++i)
dp[v]+=stu[i].v;
for(int i=0;i<G[v].size();++i){
if(G[v][i]==f)continue;
Max(dp[v],dp[G[v][i]]);
}
stu.clear();
}
inline ll Pow(int x){return 1ll*x*x;}
int main(){
cin>>n;
for(int i=1,a,b;i<n;++i){
scanf("%d %d",&a,&b);
G[a].pb(b),G[b].pb(a);
}
predfs(1,0,0);
dfs(1,0,0);
for(int i=1;i<=n;++i)
Max(ans,Pow(md[i]-1>>1));//DNA型  如样例1
cout<<ans<<endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Codeforces 树形dp