FZU Problem 2256 迷宫(dfs序)

来源:互联网 发布:虚荣辅助软件 编辑:程序博客网 时间:2024/05/16 16:05

Problem 2256 迷宫
Accept: 7 Submit: 14
Time Limit: 1500 mSec Memory Limit : 32768 KB

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序后,对于每一个点v,它的所有子节点可以通过v的传送门过来,x的儿子也可以通过边过来,过程中判断一下大小即可。
代码:

#include<iostream>#include<stdio.h>#include<stdlib.h>#include<string.h>#include<vector>#include<queue>#include<algorithm>#include<map>using namespace std;typedef long long int ll;typedef pair<int,int>pa;const int N=2e5+10;const int MOD=1e9+7;const ll INF=1e18;int read(){    int x=0;    char ch = getchar();    while('0'>ch||ch>'9')ch=getchar();    while('0'<=ch&&ch<='9')    {        x=(x<<3)+(x<<1)+ch-'0';        ch=getchar();    }    return x;}/************************************************************/struct node{    int to,next;    ll cost;} edge[N<<2];int n,p,cnt,id;ll w;ll val[N];ll dis[N];int st[N],ed[N],q[N];int head[N<<2];void init(){    cnt=0;    id=0;    memset(head,-1,sizeof(head));}void add(int u,int v,int c){    edge[cnt].to=v;    edge[cnt].cost=c;    edge[cnt].next=head[u];    head[u]=cnt++;}void redfs(int u,int fa){    st[u]=++id;    q[id]=u;    for(int i=head[u]; i!=-1; i=edge[i].next)    {        int v=edge[i].to;        if(v!=fa)        {            redfs(v,u);        }    }    ed[u]=id;}void dfs(int x,int fa){    int l=st[x];    int r=ed[x];    if(l!=r) l++;    for(int i=l;i<=r;i++)        dis[q[i]]=min(dis[q[i]],val[x]+dis[x]);    for(int i=head[x];i!=-1;i=edge[i].next)    {        int v=edge[i].to;        if(v==fa) continue;        ll c=edge[i].cost;        dis[v]=min(dis[v],dis[x]+c);        dfs(v,x);    }}int main(){    while(~scanf("%d",&n))    {        init();        for(int i=1; i<=n; i++)        {            scanf("%lld",&val[i]);            dis[i]=INF;        }        dis[1]=0;        for(int i=1; i<n; i++)        {            scanf("%d%lld",&p,&w);            add(i+1,p,w);            add(p,i+1,w);        }        redfs(1,0);        dfs(1,0);        for(int i=1; i<=n; i++)            printf("%d ",dis[i]);        printf("\n");    }    return 0;}