UVA 11174 Stand in a Line 树dp+算

简介:

主题链接:点击打开链接

题意:白书的P103.

加个虚根就能够了。。。然后就是一个多重集排列。

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;

public class Main {
	static int N = 40100;
	ArrayList<Integer>[] G = new ArrayList[N];
	static long mod = 1000000007;
	long[] way = new long[N];
	long[] fac = new long[N];
	int n, m;
	int[] father = new int[N], siz = new int[N];
	long Pow(long x, long y){
		long ans = 1;
		while(y > 0){
			if(y%2 == 1L)
				ans = (ans*x)%mod;
			x = (x*x)%mod;
			y >>= 1;
		}
		return ans;
	}
	void dfs(int u, int fa){
		siz[u] = 1; way[u] = 1L;
		for(int i = 0; i < G[u].size(); i++){
			int v = G[u].get(i); if(v == fa)continue;
			dfs(v, u);
			siz[u] += siz[v];
			way[u] = (way[u]*way[v])%mod;
		}
		way[u] = (way[u]* fac[siz[u]-1]) %mod;
		for(int i = 0; i < G[u].size(); i++){
			int v = G[u].get(i); if(v == fa)continue;
			way[u] = (way[u] * Pow(fac[siz[v]], mod-2))%mod;
		}
	}
	void init(){
		n = cin.nextInt();	m = cin.nextInt();
		for(int i = 0; i <= n; i++){
			father[i] = 0;
			G[i].clear();
		}
		while(m-- > 0){
			int u = cin.nextInt(), v = cin.nextInt();
			G[v].add(u);
			father[u] = v;
		}
		for(int i = 1; i <= n; i++)
			if(father[i] == 0){
				G[0].add(i);
			}
	}
	void work() {		
		for(int i = 0; i < N; i++)G[i] = new ArrayList();
		fac[0] = 1L;
		for(int i = 1; i < N; i++)	fac[i] = fac[i-1]*i%mod;
		int T = cin.nextInt();
		while(T-->0){
			init();
			dfs(0,0);
			out.println(way[0]);
		}
	}

	Main() {
		cin = new Scanner(System.in);
		out = new PrintWriter(System.out);
	}

	public static void main(String[] args) {
		Main e = new Main();
		e.work();
		out.close();
	}

	public Scanner cin;
	public static PrintWriter out;
}


版权声明:本文博客原创文章。博客,未经同意,不得转载。






本文转自mfrbuaa博客园博客,原文链接:http://www.cnblogs.com/mfrbuaa/p/4656190.html,如需转载请自行联系原作者


相关文章
UVa11958 - Coming Home
UVa11958 - Coming Home
51 0
UVa11565 - Simple Equations
UVa11565 - Simple Equations
53 0
uva101 The Blocks Problem
uva101 The Blocks Problem
58 0
|
人工智能
Educational Codeforces Round 98 (Rated for Div. 2)B-Toy Blocks
You are asked to watch your nephew who likes to play with toy blocks in a strange way. He has n boxes and the i-th box has ai blocks. His game consists of two steps: he chooses an arbitrary box i; he tries to move all blocks from the i-th box to other boxes.
266 0
|
前端开发
HDOJ 1212 Big Number
HDOJ 1212 Big Number
112 0
HDOJ1018Big Number
HDOJ1018Big Number
109 0
|
C++
uva 11995 I Can Guess the Data Structure!
点击打开链接uva 11995 思路: STL模拟 分析: 1 分别用三种STL去模拟这些操作,然后进行判断输出 2 比较简单 代码: #include #include #include #include #include #i...
856 0
下一篇
DataWorks