【问题背景】
zhx和他的妹子出去玩。
【问题描述】
zhx和他的妹子去一个国家旅游,共有 N 个旅游景点, N−1 条双向连接的道路将它们联通起来,每一条道路有固定长度。一开始zhx位于1号景点。
现在希望你能够求出旅行长度最小的方案,使得每个景点至少被访问到一次。
【输入格式】
第一行两个整数 N ,代表景点数目。
接下来 N−1 行,每行三个整数 s , t , w ,表示有一条从 s 到 t 的双向道路,长度为 w 。 s 和 t 的编号从1开始。
【输出格式】
一行一个整数,代表能够访问每个景点至少一次的方案的最小旅行长度。
【样例输入】
3
1 2 3
2 3 33
1 2 3
1 3 3
【样例输出】
6
9
【数据范围与规定】
这道题,据说有树形DP做法(显然),但懒惰的我歪歪了一个贪心(手玩数据好处多(逃~)),后来发现很多人也这么写的,好吧我还是太弱了。对于30%的数据, 1≤N≤10 。
对于70%的数据, 1≤N≤1000 。
对于100%的数据, 1≤N≤50000,1≤w≤1000 。
这个贪心就是所有边的权值的两倍减去从1出发的最长的一条链的长度即为答案,正确性比较容易证明,留给自己想想吧。
代码如下:
#include <iostream>
#include <cstdio>
#include <vector>
using namespace std;
inline int read(void){
int x=0,f=1; char ch=getchar();
for(;ch<'0'||ch>'9';ch=getchar()) if(ch=='-') f=-1;
for(;ch>='0'&&ch<='9';x=(x<<3)+(x<<1)+ch-'0',ch=getchar());
return x*f;
}
const int maxn=50009;
struct LJM{
int to,w;
}; vector<LJM>f[maxn];
int dis[maxn];
void dfs(int x,int fa){
for(int i=0;i<f[x].size();i++){
int to=f[x][i].to;
if(to==fa) continue;
dfs(to,x);
dis[x]=max(dis[x],dis[to]+f[x][i].w);
}
}
int main(int argc,char const *argv[]){
int n=read(),sum=0;
for(int i=1;i<n;i++){
int a=read(),b=read(),c=read();
sum+=c;
f[a].push_back((LJM){b,c});
f[b].push_back((LJM){a,c});
}
dfs(1,-1);
cout<<sum*2-dis[1]<<endl;
return 0;
}