Hdu 2196 Computer

來源:互聯網
上載者:User

標籤:

題意:給你一棵樹,讓你求出每個點離樹上最遠的距離.

...不會做,想了半天查了題解。

對於每一個點最遠距離,要麼是往下走,要麼是從父節點下來的。

dp[u][0]表示跑兒子路的最大值,dp[u][1]表示跑兒子路的次大值.為什麼要記錄次大值呢。

dp[u][2]表示往父親那裡跑的最大值.

dp[v][2]照常理來說應該是等於max(dp[u][0],dp[u][2])+w[u][v].但是dp[u][0]有可能是從dp[v][0]那裡得到的,如那種情況dp[u][0]就是跑向v的那裡.這種情況下就要用max(dp[u][1],dp[u][2])+w[u][v];

#include <iostream>#include <cstdio>#include <cstring>#include <ctime>#include <algorithm>#include <cstdlib>#include <cmath>#include <map>#include <vector>#include <set>using namespace std;typedef long long ll;typedef unsigned long long ull;typedef double db;#define X first#define Y second#define mp(a,b) make_pair(a,b)#define pb push_back#define sd(x) scanf("%d",&(x))#define Pi acos(-1.0)#define sf(x) scanf("%lf",&(x))#define ss(x) scanf("%s",(x))#define maxn 10005const int inf=0x3f3f3f3f;const ll mod=1000000007;struct node{    int v,w,next;}E[maxn];int top;int head[maxn];void add(int u,int v,int w){    E[top].v=v;    E[top].w=w;    E[top].next=head[u];    head[u]=top++;}int dp[maxn][3];void dfs(int u){    int mm=0,sm=0,v,pa;    for(int i=head[u];i!=-1;i=E[i].next)    {        v=E[i].v;        dfs(v);        pa=dp[v][0]+E[i].w;        if(pa>=mm)        {            sm=mm;            mm=pa;        }        else if(pa>=sm)            sm=pa;    }    dp[u][0]=mm;    dp[u][1]=sm;}void dfs2(int u){    int v;    for(int i=head[u];i!=-1;i=E[i].next)    {        v=E[i].v;        dp[v][2]=max(dp[u][2],dp[v][0]+E[i].w==dp[u][0]?dp[u][1]:dp[u][0])+E[i].w;        dfs2(v);    }}int main(){#ifdef local    freopen("in","r",stdin);    //freopen("out","w",stdout);    int _time=clock();#endif    int n;    while(cin>>n){            top=0;    memset(head,-1,sizeof head);    for(int v=2;v<=n;v++)    {        int u,w;        scanf("%d%d",&u,&w);        add(u,v,w);    }    dfs(1);    dp[1][2]=0;    dfs2(1);    for(int i=1;i<=n;i++)    {        printf("%d\n",max(dp[i][0],dp[i][2]));    }    }#ifdef local    printf("time: %d\n",int(clock()-_time));#endif}
View Code

 

Hdu 2196 Computer

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.