LuoguP3047 [USACO12FEB]附近的牛Nearby Cows(树形DP,容斥)

\[f[u][step] = \begin{cases} C[u] & step = 0 \\ (\sum{f[v][step - 1]}) - f[u][step - 2] \cdot (deg[u] - 1) & 1 \leq step < maxSteps \end{cases}\]

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#define R(a,b,c) for(register int  a = (b); a <= (c); ++ a)
#define nR(a,b,c) for(register int  a = (b); a >= (c); -- a)
#define Max(a,b) ((a) > (b) ? (a) : (b))
#define Min(a,b) ((a) < (b) ? (a) : (b))
#define Fill(a,b) memset(a, b, sizeof(a))
#define Abs(a) ((a) < 0 ? -(a) : (a))
#define Swap(a,b) a^=b^=a^=b
#define ll long long

#define ON_DEBUG

#ifdef ON_DEBUG

#define D_e_Line printf("\n\n----------\n\n")
#define D_e(x)  cout << #x << " = " << x << endl
#define Pause() system("pause")
#define FileOpen() freopen("in.txt","r",stdin);

#else

#define D_e_Line ;
#define D_e(x)  ;
#define Pause() ;
#define FileOpen() ;

#endif

struct ios{
    template<typename ATP>ios& operator >> (ATP &x){
        x = 0; int f = 1; char c;
        for(c = getchar(); c < '0' || c > '9'; c = getchar()) if(c == '-')  f = -1;
        while(c >= '0' && c <= '9') x = x * 10 + (c ^ '0'), c = getchar();
        x*= f;
        return *this;
    }
}io;
using namespace std;

const int N = 100007;

int n, K;

struct Edge{
    int nxt, pre;
}e[N << 1];
int head[N], cntEdge;
inline void add(int u, int v){
    e[++cntEdge] = (Edge){ head[u], v}, head[u] = cntEdge;
}

int f[N][23];
int in[N];
int main(){
    io >> n >> K;
    R(i,2,n){
        int u, v;
        io >> u >> v;
        add(u, v),
        add(v, u),
        ++in[u],
        ++in[v];
    }
    
    R(i,1,n){
        io >> f[i][0];
    }
    
    R(k,1,K){
        R(u,1,n){
            for(register int i = head[u]; i; i = e[i].nxt){
                f[u][k] += f[e[i].pre][k - 1];
            }
            if(k > 1)
                f[u][k] -= f[u][k - 2] * (in[u] - 1);
            else
                f[u][k] += f[u][0];
        }
    }
    
    R(i,1,n){
        printf("%d\n", f[i][K]);
    }
    
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/bingoyes/p/11252586.html