zoukankan      html  css  js  c++  java
  • 牛客网暑期ACM多校训练营(第三场)G:Coloring Tree(函数的思想)

    之前两次遇到过函数的思想的题,所以这次很敏感就看出来了。可以参考之前的题:

        https://www.cnblogs.com/hua-dong/p/9291507.html

    Christmas is coming! Eddy has received a Christmas tree as gift. Not surprisingly, the tree consists of N vertices and N-1 edges and magically remains connected. Currently, all the vertex of the tree is uncolored. Eddy wants to color each vertex into one of K colors. However, there are too many way to color the tree(i.e. KN ways). Eddy doesn't want the result of coloring being too boring. Thus, he defines the colorness of a tree as follow:

    The colorness of a tree is the minimum distance between two vertex colored in the same color.

    Now, Eddy is wondering how many way to color the tree such that the colorness of the tree will be D.


    The first line of input contains three space-separated integer N, K, D indicating the number of vertices, number of colors, and the required colorness.
    For each following N-1 lines, each contains two space-separated positive integer ui, vi indicating that there's an edge between ui and vi.

    1 ≤ K < N ≤ 5000
    1 ≤ D ≤ N
    1 ≤ ui < vi ≤ N
    It's guaranteed that the given input is a tree.

    题意:用K种颜色给树染色,问有多少种染色方案,使得min{同色间距离}=D。

    思路:一眼题,但是当时没时间了,4点就出门了。晚上一会就补了,emmm。

    还是函数的思想,令F(X)表示距离在X内的点都不同色。那么只要在搜索的同时(BFS或者DFS都可以)染色即可。

    如果对S点染色,在X范围内的有Y个点染色了,那么S点的染色种类数为K-Y,回去搜索一下已经染过色的有多少就行了,复杂度为O(N^2)。

    #include<bits/stdc++.h>
    #define ll long long
    using namespace std;
    const int Mod=1e9+7,maxn=10010;
    int Next[maxn],Laxt[maxn],To[maxn],cnt;
    int K,q[maxn],col[maxn],head,tail,ans;
    void add(int u,int v){ Next[++cnt]=Laxt[u]; Laxt[u]=cnt; To[cnt]=v; }
    int dfs(int u,int f,int dis){
        int res=1; 
        for(int i=Laxt[u];i;i=Next[i]) 
          if(To[i]!=f&&col[To[i]]&&dis>0) res+=dfs(To[i],u,dis-1);
        return res;
    }
    int cal(int D)
    {
        int res=1; memset(col,0,sizeof(col)); head=tail=0;
        q[++head]=1; 
        while(tail<head){
            int u=q[++tail]; col[u]=1;
            int num=dfs(u,0,D);
            res=(ll)res*(K+1-num)%Mod;
            for(int i=Laxt[u];i;i=Next[i]) if(!col[To[i]]) q[++head]=To[i];
        }
        return res;
    }
    int main()
    {
        int N,D,u,v,i;
        while(~scanf("%d%d%d",&N,&K,&D)){
            cnt=0; ans=0; head=0; tail=0;
            memset(Laxt,0,sizeof(Laxt));
            for(i=1;i<N;i++) scanf("%d%d",&u,&v),add(u,v),add(v,u);
            printf("%d
    ",(cal(D-1)-cal(D)+Mod)%Mod);
        }
        return 0;
    }
  • 相关阅读:
    聊一聊分布式锁的设计
    github上值得关注的前端项目
    数据库水平切分的实现原理解析——分库,分表,主从,集群,负载均衡器(转)
    查询执行时间
    Autofac in webapi2
    Fluent Validation with Web Api 2
    数字转换成大写
    ABP:在多语句事务内不允许使用 CREATE DATABASE 语句
    陕西电力同业对标管理系统
    多媒体文件嵌入HTML中自动转码工具
  • 原文地址:https://www.cnblogs.com/hua-dong/p/9374975.html
Copyright © 2011-2022 走看看