洛谷P3931“tree”题解
——作者:岸芷汀兰
一、题目:
题目背景
冴月麟和魏潇承是好朋友。
题目描述
冴月麟为了守护幻想乡,而制造了幻想乡的倒影,将真实的幻想乡封印了。任何人都无法进入真实的幻想乡了,但是她给前来救她的魏潇承留了一个线索。
她设置了一棵树(有根)。树的每一条边上具有割掉该边的代价。
魏潇承需要计算出割开这棵树的最小代价,这就是冴月麟和魏潇承约定的小秘密。
帮帮魏潇承吧。
注:所谓割开一棵有根树,就是删除若干条边,使得任何任何叶子节点和根节点不连通。
输入输出格式
输入格式:
输入第一行两个整数n,S表示树的节点个数和根。
接下来n-1行每行三个整数a、b、c,表示a、b之间有一条代价为c的边。
输出格式:
输出包含一行,一个整数,表示所求最小代价。
输入输出样例
输入样例#1:
4 1
1 2 1
1 3 1
1 4 1
输出样例#1:
3
输入样例#2:
4 1
1 2 3
2 3 1
3 4 2
输出样例#2:
1
说明
对于20%的数据,n <= 10
对于50%的数据,n <= 1000
对于100%的数据,n <= 100000
二、思路
这个题的实质就是深度优先搜索,在搜索的时候顺便跑一个DP。每次比较这条边的权值与这条边的子树的边的权值的总和,如果小于,就把子树权值总和赋给这条边,更新,这样就能保证最小(最优)
三、注意
搜索时要注意特判。调试的时候尽量用输出调试。
四、代码
//luogu P3931
#include<iostream>
#include<cstdio>
#include<vector>
typedef long long ll;
using namespace std;
inline int read(){
int x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=10*x+ch-'0';ch=getchar();}
return x*f;
}
const int maxn=100005;
struct Node{
int y,w;
};
vector<Node>q[2*maxn];
int n,S;
int dfs(int,int);
int main()
{
scanf("%d%d",&n,&S);
for(int i=1;i<n;i++){
int x,y,w;
scanf("%d%d%d",&x,&y,&w);
q[y].push_back((Node){x,w});
q[x].push_back((Node){y,w});
}
cout<<dfs(S,-1);
return 0;
}
int dfs(int u,int fa){
//cout<<"u:"<<u<<endl;
int ans=0;
bool flag=0;
for(int i=0;i<q[u].size();i++){
int v=q[u][i].y;
if(v==fa)continue;
flag=true;
int temp=-1e9;
temp=dfs(v,u);
if(temp==-1){/*cout<<"!!!";*/temp=q[u][i].w;ans+=temp;continue;}
if(temp<q[u][i].w){
q[u][i].w=temp;
}
ans+=q[u][i].w;
}
if(flag)return ans;
else {
//cout<<"!!!";
return -1;
}
}
不要Ctrl+C哦!