惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

美团技术团队
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Martin Fowler
Martin Fowler
雷峰网
雷峰网
IT之家
IT之家
小众软件
小众软件
M
MIT News - Artificial intelligence
博客园 - 聂微东
J
Java Code Geeks
Blog — PlanetScale
Blog — PlanetScale
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
A
About on SuperTechFans
G
Google Developers Blog
Engineering at Meta
Engineering at Meta
Recent Announcements
Recent Announcements
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
The GitHub Blog
The GitHub Blog
F
Fortinet All Blogs
C
Check Point Blog
云风的 BLOG
云风的 BLOG
腾讯CDC
H
Help Net Security
Y
Y Combinator Blog
I
InfoQ

博客园 - ZefengYao

Markdown 入门与 Word 使用指南 关于崩溃报告的日志以及dump文件 hdu 6223 Infinite Fraction Path 2017南宁现场赛E The Champion ACM-ICPC 2018 南京赛区网络预赛 Sum c语言几个字符串处理函数的简单实现 各种类型排序的实现及比较 随机洗牌算法Knuth Shuffle和错排公式 两个栈实现队列 面试杂题 面试题——栈的压入、弹出顺序 C++ 智能指针的简单实现 openGL初学函数解释汇总 foj Problem 2107 Hua Rong Dao foj Problem 2282 Wand UVA-1400 Ray, Pass me the dishes! 《挑战程序设计竞赛》 利用后缀数组求最长回文串 UVA 11375 Matches poj 3729 Facer’s string
Uva 11174 Stand in a Line
ZefengYao · 2018-05-24 · via 博客园 - ZefengYao

Stand in a Line Uva 11174

题意:把n个人排成一列,使得没有人排在他父亲的前面,输出方案数MOD 1000000007

思路:《算法竞赛入门经典》P 111

AC代码:

#define _CRT_SECURE_NO_DEPRECATE
#include<iostream>
#include<vector>
#include<algorithm>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<string>
using namespace std;
const int N_MAX = 40000 + 20;
const int MOD = 1000000007;
typedef long long ll;
int num[N_MAX];//记忆化搜索以,i为根节点的子树的节点数量
int e_gcd(int a,int b,int &x,int &y) {
    if (b == 0) {
        x = 1; y = 0;
        return a;
    }
    int ans = e_gcd(b,a%b,x,y);
    int temp = x;
    x = y;
    y = temp - a / b*y;
    return ans;
}

int mod_inverse(int a,int m) {
    int x, y;
    e_gcd(a,m,x,y);
    return (m + x%m) % m;
}
int n, m;
vector<int>G[N_MAX];

int dfs(int x) {//寻找以x为根的子树的节点数量
    if (num[x])return num[x];
    for (int i = 0; i < G[x].size();i++) {
        num[x] += dfs(G[x][i]);
    }
    return ++num[x];
}

int main() {
    int t; scanf("%d",&t);
    while (t--) {
        scanf("%d%d",&n,&m);
        memset(num,0,sizeof(num));
        for (int i = 0; i <n; i++)G[i].clear();
        for (int i = 0; i < m;i++) {
            int a, b; scanf("%d%d", &a, &b); a--, b--;
            G[b].push_back(a);
        }
        ll N = 1;
        for (int i = 2; i <= n;i++) {
            N = N*i%MOD;
        }
        ll mul = 1;
        for (int i = 0; i < n;i++) {
            mul = mul*dfs(i)%MOD;
        }
        ll ans = N*mod_inverse(mul, MOD) % MOD;
        printf("%lld\n",ans);
    }
    return 0;
}