POJ 1985牛マラソン

リンク
問題の意味:
Nツリーのエッジ重み直径(最長鎖ツリー)を探している
アイデアを:
ルートは、必要に応じて、と呼ばれるまずこと(ルート\)\とハチソン \(DP [X]は、\)である(\ X \)すべてのノードの最大値とその下方経路を開始
ツリーDPため
\(DP [I] = \最大\ limits_ {ソンでJ \(I)}(DP [I]、W [I] [ J] + DP [J])
\) 我々は、実際には、ツリーの直径が最大値と最大第二値と経路長の出発点であり、2つの側パスが繰り返されないことを確認することができ
、我々は木DPを行います下部からの遷移で \(RES \)に更新される:
\(RES = \最大\ limits_ {J \ソン(I)における}(RES、DP [I] + DP [J] + W [I] [ J])\)
コード:

#include<iostream>

using namespace std;

const int N=4e4+5;
const int M=8e4+5;

int n,m;
int cnt;
int to[M],val[M],nxt[M],head[N];
bool st[N];
int dp[N];
int res;

void addedge(int u,int v,int w) {
    cnt++;
    to[cnt]=v;
    val[cnt]=w;
    nxt[cnt]=head[u];
    head[u]=cnt;
}
void dfs(int u) {
    st[u]=true;
    for(int i=head[u];i;i=nxt[i]) {
        int v=to[i],w=val[i];
        if(st[v]) continue;
        dfs(v);
        res=max(res,dp[u]+dp[v]+w);
        dp[u]=max(dp[u],dp[v]+w);
    }   
}
int main() {
    //freopen("in.txt","r",stdin);
    ios::sync_with_stdio(false);
    cin.tie(0);
    cin>>n>>m;
    for(int i=1;i<=m;i++) {
        int u,v,w;
        char c;
        cin>>u>>v>>w>>c;
        addedge(u,v,w);
        addedge(v,u,w);
    } 
    dfs(1);
    cout<<res<<endl;
    return 0;
}

おすすめ

転載: www.cnblogs.com/c4Lnn/p/12381330.html