迷宫
Problem Description
某一天,YellowStar在人生的道路上迷失了方向,迷迷糊糊之中,它误入了一座迷宫中,幸运的是它在路口处发现了一张迷宫的地图。
经过它的观察,它发现这个迷宫一共有n个房间,并且这n个房间呈现一个有根树结构,它现在所在的1号房间为根,其它每个房间都有一个上级房间,连接第i个房间和它的上级房间Pi的道路长度为Wi。
在地图的背面,记载了这个迷宫中,每个房间拥有一个时空传送门,第i个房间的传送门可以花费Di单位的时间传送到它的任意一个下级房间中(如果x是y的下级房间,并且y是z的下级房间,那么x也是z的下级房间)。
YellowStar的步行速度为1单位时间走1长度,它现在想知道从1号房间出发,到每一个房间的最少时间。
Input
包含多组测试数据。
第一行输入n表示n个房间。
第二行输出n个数字,第i个数字Di表示i号房间传送器需要花费的时间。
接下来n-1行,第i行包含两个数字Pi和Wi,表示i+1号房间的上级房间为Pi,道路长度为Wi。
1≤n≤100000
1≤Di, Wi≤10^9
Output
输出n个数,第i个数表示从1号房间出发到i号房间的最少时间。 (注意,输出最后一个数字后面也要加一个空格)
Sample Input
5
99 97 50 123 550
1 999
1 10
3 100
3 44
Sample Output
0 99 10 60 54
Hint
初始在1号房间,到1号房间的代价为0。
通过1号房间的传送门传送到2号房间,到2号房间的代价为99。
通过1号房间走到3号房间,到3号房间的代价为10。
通过1号房间走到3号房间,在通过3号房间的传送门传送到4号房间,到4号房间的代价为60。
通过1号房间走到3号房间,在通过3号房间走到5号房间,到5号房间的代价为54。
思路:
直接建树,然后dfs遍历这棵树,同时记录到每一点最小花费即可
代码:
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
const int inf=0x3f3f3f3f;
const int maxn=1000000+10;
struct node
{
int v,w,next;
}E[maxn];
int a[maxn],b[maxn],first[maxn],ans[maxn];
int n,len;
void dfs(int rt,int cost1,int cost2)//cost1代表从上级直接传送的花费,cost2代表从父节点走过来的花费
{
ans[rt]=min(cost1,cost2);
for(int i=first[rt];~i;i=E[i].next)
{
int v=E[i].v,w=E[i].w;
int tot=min(ans[rt]+a[rt],cost1);
dfs(v,tot,ans[rt]+b[v]);
}
}
void add_edge(int u,int v,int w)
{
E[len].v=v,E[len].w=w;
E[len].next=first[u];
first[u]=len++;
}
int main()
{
int x;
while(~scanf("%d",&n))
{
memset(first,-1,sizeof(first));
len=0;
for(int i=1; i<=n; ++i)
scanf("%d",&a[i]);
for(int i=2; i<=n; ++i)
{
scanf("%d%d",&x,&b[i]);
add_edge(x,i,b[i]);
}
dfs(1,inf,0);
for(int i=1;i<=n;++i)
printf("%d ",ans[i]);
puts("");
}
return 0;
}