标签:dp
Bob is going to create a graph with N nodes. The graph will be constructed in two steps. First, Bob will take N isolated vertices, label them 1 through N and color each of them using one of K colors. Then, Bob will add some directed edges to the graph. For each i between 2 and N, inclusive, Bob may choose a single value j < i such that the nodes i and j have different colors. If he does, he will add the edge from i to j to his graph. Note that Bob may choose not to add any edge from node i, even if there are some valid choices of j.
Two graphs are considered the same if they have the same node colors and the same set of edges.
You are given the ints N and K. Compute and return the number of different graphs Bob may construct, modulo 1,000,000,007.
492594064
There can be at most 3 colors. So how about we solve for 3 colors, then we can adapt the solution for fewer number of colors with small tweaks.
The problem statement describes the decision as first choosing colors and then creating the edges. But the actual rules for counting the unique setups combines the two together. Let‘s try to make the decision about picking a color AND an edge for each vertex.
Imagine we‘ve already picked colors and edges for the first
The idea is that we can just increment the count of the respective color and move on to the next
When there are two colors, we can just disable the part where we pick color
When there is one color, we can just return the number of graphs of size
The idea with that recurrence relation is that it is acyclic and the number of states is not very large
const int MOD = 1000000007; int dp[101][101][101]; int N, K; int f(int a, int b, int c) { int & res = dp[a][b][c]; if (res == -1) { if (a + b + c == N) { // the end res = 1; } else { res = 0; long p, q; // color vertex with color a p = 1 + b + c; q = f(a + 1, b, c); res += (int)( (p * q) % MOD ); res %= MOD; // color vertex with color b if (K >= 2) { p = 1 + a + c; q = f(a, b + 1, c); res += (int)( (p * q) % MOD ); res %= MOD; } // color vertex with color c if (K >= 3) { p = 1 + a + b; q = f(a, b, c + 1); res += (int)( (p * q) % MOD ); res %= MOD; } } } return res; } int countWays(int N, int K) { this->N = N; this->K = K; memset(dp, -1, sizeof(dp)); return f(0,0,0); }
版权声明:本文为博主原创文章,未经博主允许不得转载。
DP SRM 661 Div2 Hard: ColorfulLineGraphsDiv2
标签:dp
原文地址:http://blog.csdn.net/acm_10000h/article/details/47071629
The 24 different graphs are shown below. In each picture, the vertices have labels 1, 2, 3 from the left to the right.