【Codeforces 1156E】 0-1-Tree 樹形dp

題目大意:

給出一棵樹,沒條邊具有邊權0/1,求出真路徑的數量

真路徑(x,y):x->y的路徑上,如果經過了1,則之後不能經過0

題目思路:

考慮最終合法的路徑數量:

1000 000 111

由這幾種路徑數量去狀態壓縮:dp[i][k] 表示 從i節點出髮狀態爲k的路徑數量

狀態轉移方程的推法:

如果當前邊爲1,那麼從該節點出發一定爲10 11 與 00 01 無關

如果當前邊爲0,那麼從該節點出發一定爲00 01 與11 10 無關

最後考慮合併時產生的貢獻(這個地方很複雜,建議畫圖看)

Note:11 00 貢獻爲2 (x,y) (y,x)都可以,10 01 貢獻爲1 只有01可以

Code:

/*** keep hungry and calm CoolGuang!***/
#pragma GCC optimize(2)
#pragma GCC optimize("Ofast","unroll-loops","omit-frame-pointer","inline")
#include <bits/stdc++.h>
#include<stdio.h>
#include<queue>
#include<algorithm>
#include<string.h>
#include<iostream>
#define debug(x) cout<<#x<<":"<<x<<endl;
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const ll INF=1e18;
const int maxn=1e6+6;
const int mod=998244353;
const double eps=1e-15;
inline bool read(ll &num)
{char in;bool IsN=false;
    in=getchar();if(in==EOF) return false;while(in!='-'&&(in<'0'||in>'9')) in=getchar();if(in=='-'){ IsN=true;num=0;}else num=in-'0';while(in=getchar(),in>='0'&&in<='9'){num*=10,num+=in-'0';}if(IsN) num=-num;return true;}
ll n,m,p;
vector<pair<int,int>>v[maxn];
ll dp[maxn][4];///00 01 10 11
ll ans = 0;
void dfs(int u,int fa){

    for(auto x:v[u]){
        int e = x.first;
        if(e == fa) continue;
        dfs(e,u);
        //printf("father:%d->son:%d------------\n",u,e);
        if(!x.second){

            ans += dp[u][0]*(dp[e][0]+1)*2;///00

            ans += (dp[u][1]+dp[u][3])*(dp[e][0]+1);///10

            ans += dp[u][0]*(dp[e][1]+dp[e][3]);///01

            dp[u][0] += dp[e][0] + 1;///00
            dp[u][1] += dp[e][1] + dp[e][3];///01
        }
        else{
            ans += (dp[u][2]+dp[u][0])*(dp[e][3]+1);///01

            ans += dp[u][3]*(dp[e][3]+1)*2;///11

            ans += dp[u][3]*(dp[e][2]+dp[e][0]);///10
            
            dp[u][2] += dp[e][0] + dp[e][2];///10 = 1 + 0 1+10
            dp[u][3] += dp[e][3] + 1;
        }
        //debug(ans);
    }
    for(int i=0;i<4;i++){
        if(i==0||i==3) ans += 2*dp[u][i];
        else ans += dp[u][i];
    }
}
int main(){
    read(n);
    for(int i=1;i<=n-1;i++){
        int x,y,z;scanf("%d%d%d",&x,&y,&z);
        v[x].push_back({y,z});
        v[y].push_back({x,z});
    }
    dfs(1,1);
    printf("%lld\n",ans);
    return 0;
}
/**
22+1+2+1+2+4+2
**/

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章