[USACO17DEC] Barn Painting

Posted 蒟蒻JHY

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[USACO17DEC] Barn Painting相关的知识,希望对你有一定的参考价值。

题目描述

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的主要内容,如果未能解决你的问题,请参考以下文章

bzoj1730[Usaco2005 dec]Barn Expansion 牛棚扩张

[USACO 2017DEC] Barn Painting

[USACO 12DEC]Running Away From the Barn

BZOJ3011[Usaco2012 Dec]Running Away From the Barn 可并堆

bzoj3011[Usaco2012 Dec]Running Away From the Barn*

USACO 1.3Barn Repair