码迷,mamicode.com
首页 > 其他好文 > 详细

[USACO17DEC] Barn Painting

时间:2018-02-17 19:40:50      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:each   ber   path   app   nta   guarantee   res   ora   orm   

题目描述

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

标签:each   ber   path   app   nta   guarantee   res   ora   orm   

原文地址:https://www.cnblogs.com/JYYHH/p/8452096.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!