[USACO17DEC] Barn Painting

本文探讨了在大型农场中,对于N个谷仓使用三种颜色进行染色的问题。目标是在确保直接相连的谷仓不使用相同颜色的前提下,计算所有合法染色方案的数量。文章提供了一种基于树形DP的方法,并附带了完整的代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述

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-1N1 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;
}

  



转载于:https://www.cnblogs.com/JYYHH/p/8452096.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值