1. 程式人生 > >[USACO17DEC] Barn Painting

[USACO17DEC] Barn Painting

ott which long long urn spec cow use vector 難度

題目描述

Farmer John has a large farm with NN barns (1 \le N \le 10^51N105 ), some of which are already painted and some not yet painted. Farmer John wants to paint these remaining barns so that all the barns are painted, but he only has three paint colors available. Moreover, his prize cow Bessie becomes confused if two barns that are directly reachable from one another are the same color, so he wants to make sure this situation does not happen.

It is guaranteed that the connections between the NN barns do not form any ‘cycles‘. That is, between any two barns, there is at most one sequence of connections that will lead from one to the other.

How many ways can Farmer John paint the remaining yet-uncolored barns?

輸入輸出格式

輸入格式:

The first line contains two integers NN and KK (0 \le K \le N0KN ), respectively the number of barns on the farm and the number of barns that have already been painted.

The next N-1N?1 lines each contain two integers xx and yy (1 \le x, y \le N, x \neq y1x,yN,xy ) describing a path directly connecting barns xx and yy .

The next KK lines each contain two integers bb and cc (1 \le b \le N1bN , 1 \le c \le 31c3 ) indicating that barn bb is painted with color cc .

輸出格式:

Compute the number of valid ways to paint the remaining barns, modulo 10^9 + 7109+7 , such that no two barns which are directly connected are the same color.

輸入輸出樣例

輸入樣例#1:
4 1
1 2
1 3
1 4
4 3

輸出樣例#1:
8


樹上dp求相鄰節點不同的染色方案。
已染色的就把該節點的其他顏色的方案數置為0即可。
(這個難度評價有毒,把我騙進來了hhhh)

#include<bits/stdc++.h>
#define ll long long
#define maxn 100005
#define pb push_back
using namespace std;
const int ha=1000000007;
vector<int> g[maxn];
int f[maxn][4],col[maxn];
int n,m,k,ans;

inline int add(int x,int y){
    x+=y;
    if(x>=ha) return x-ha;
    else return x;
}

void dfs(int x,int fa){
    f[x][1]=f[x][2]=f[x][3]=1;
    
    int to,tmp;
    for(int i=g[x].size()-1;i>=0;i--){
        to=g[x][i];
        if(to==fa) continue;
        
        dfs(to,x);
        
        tmp=add(f[to][1],add(f[to][2],f[to][3]));
        for(int j=1;j<=3;j++) f[x][j]=f[x][j]*(ll)add(tmp,ha-f[to][j])%ha;
    }
    
    if(col[x]){
        for(int i=1;i<=3;i++) if(i!=col[x]) f[x][i]=0;
    }
}

int main(){
    int uu,vv;
    scanf("%d%d",&n,&k);
    for(int i=1;i<n;i++){
        scanf("%d%d",&uu,&vv);
        g[uu].pb(vv),g[vv].pb(uu);
    }
    for(int i=1;i<=k;i++){
        scanf("%d%d",&uu,&vv);
        col[uu]=vv;
    }
    
    dfs(1,0);
    
    ans=add(add(f[1][2],f[1][1]),f[1][3]);
    printf("%d\n",ans);
    
    return 0;
}

  



[USACO17DEC] Barn Painting