先求出树的最远点对(树的直径)d1,d2,再求出以直径的两个端点为起点的dist[i](起点到i的距离),首先将直径(d1,d2的距离)加入集合,对于其他点i,加入max(d1到i的距离,d2到i的距离)到集合,集合所构成的树就是题目的答案
交了n次都wa了,对拍了一个下午,结果发现是没选择c++11,记住这次惨痛的教训
#include<cstdio>
#include<cstring>
#include<vector>
#define ll long long
#define Max(a,b) a>b?a:b
using namespace std;
struct edge
{
int to,w;
};
const int maxn = 1e5+10;
vector<edge> g[maxn];
int vis[maxn];
ll dist1[maxn],dist2[maxn];
ll pos1,pos2,max1;
void addedge(int from,int to,int w)
{
g[to].push_back(edge{from,w});
g[from].push_back(edge{to,w});
}
void dfs(int s,ll d,ll *dis)
{
vis[s]=1;
dis[s]=d;
for(int i=0;i<g[s].size();i++)
// for(int i=g[s].size()-1;i>=0;i--)
{
int v=g[s][i].to;
int w=g[s][i].w;
if(!vis[v])
{
dfs(v,d+w,dis);
}
}
}
int main()
{
int n;
//freopen("in.txt","r",stdin);
while(scanf("%d",&n)!=EOF)
{
int a,b,c;
for(int i=1;i<=n;i++)g[i].clear();
for(int i=0;i<n-1;i++)
{
scanf("%d%d%d",&a,&b,&c);
addedge(a,b,c);
}
memset(vis,0,sizeof(vis));
dfs(1,0,dist1);
max1=0;
for(int i=1;i<=n;i++)
if(max1<dist1[i])
{
max1=dist1[i];pos1=i;//找到直径的一端
}
max1=0;
memset(vis,0,sizeof(vis));
dfs(pos1,0,dist1);
for(int i=1;i<=n;i++)
if(max1<dist1[i])
{
max1=dist1[i];pos2=i;//找到直径的另一端
}
memset(vis,0,sizeof(vis));
dfs(pos2,0,dist2);
ll ans = dist1[pos2];
for(int i=1;i<=n;i++)
{
if(i!=pos1&&i!=pos2)ans+=Max(dist1[i],dist2[i]);
}
printf("%lld\n",ans);
}
}
#include<cstdio>
#include<cstring>
#include<vector>
#define ll long long
#define Max(a,b) a>b?a:b
using namespace std;
struct edge
{
int to,w;
};
const int maxn = 1e5+10;
vector<edge> g[maxn];
int vis[maxn];
ll dist1[maxn],dist2[maxn];
ll pos1,pos2,max1;
void addedge(int from,int to,int w)
{
g[to].push_back(edge{from,w});
g[from].push_back(edge{to,w});
}
void dfs(int s,ll d,ll *dis)
{
vis[s]=1;
dis[s]=d;
for(int i=0;i<g[s].size();i++)
// for(int i=g[s].size()-1;i>=0;i--)
{
int v=g[s][i].to;
int w=g[s][i].w;
if(!vis[v])
{
dfs(v,d+w,dis);
}
}
}
int main()
{
int n;
//freopen("in.txt","r",stdin);
while(scanf("%d",&n)!=EOF)
{
int a,b,c;
for(int i=1;i<=n;i++)g[i].clear();
for(int i=0;i<n-1;i++)
{
scanf("%d%d%d",&a,&b,&c);
addedge(a,b,c);
}
memset(vis,0,sizeof(vis));
dfs(1,0,dist1);
max1=0;
for(int i=1;i<=n;i++)
if(max1<dist1[i])
{
max1=dist1[i];pos1=i;//找到直径的一端
}
max1=0;
memset(vis,0,sizeof(vis));
dfs(pos1,0,dist1);
for(int i=1;i<=n;i++)
if(max1<dist1[i])
{
max1=dist1[i];pos2=i;//找到直径的另一端
}
memset(vis,0,sizeof(vis));
dfs(pos2,0,dist2);
ll ans = dist1[pos2];
for(int i=1;i<=n;i++)
{
if(i!=pos1&&i!=pos2)ans+=Max(dist1[i],dist2[i]);
}
printf("%lld\n",ans);
}
}