BZOJ4011: [HNOI2015] falling memory Fengyin (dp multiplication principle)

Keywords: C++

meaning of the title

Title Link

Sol

A wonderful question

Set \ (inder[i] \) to represent the degree of \ (I \) node

First of all, if it is a DAG, you can consider selecting an edge from the incoming edge of each point as the edge on the tree graph, so \ (ANS = \ prod {I > 1} inder [i] \)

If an edge is added, the contribution of some rings (such as \ (2 - 4 - 3 \) in the example) may be included in the solution

Consider the contribution on the subtractive ring. Note that there is more than one ring. To be exact, if \ (x - > y \) edge is added, the contribution should be calculated for all \ (Y - > x \) paths in the original graph

The contribution of one path is \ (\ frac {ans} {s \ in (Y - > x) inder [S]} \)

dp can calculate all the contributions once

#include<bits/stdc++.h>
using namespace std;
const int MAXN = 1e6 + 10, mod = 1e9 + 7;
inline int read() {
    char c = getchar(); int x = 0, f = 1;
    while(c < '0' || c > '9') {if(c == '-') f = -1; c = getchar();}
    while(c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
    return x * f;
}
int N, M, X, Y, inder[MAXN], inv[MAXN], t[MAXN], f[MAXN];
vector<int> v[MAXN];
void add(int &x, int y) {
    if(x + y < 0) x = x + y + mod;
    else x = (x + y >= mod ? x + y - mod : x + y);
}
int mul(int x, int y) {
    return 1ll * x * y % mod;
}
void Topsort() {
    queue<int> q;
    for(int i = 1; i <= N; i++) if(!inder[i]) q.push(i); 
    while(!q.empty()) {
        int p = q.front(); q.pop(); f[p] = mul(f[p], inv[t[p]]); 
        for(int i = 0; i < v[p].size(); i++) {
            int to = v[p][i];
            add(f[to], f[p]); 
            if(!(--inder[to])) q.push(to);
        }
    }
}
int main() {
    N = read(); M = read(); X = read(); Y = read();
    inv[1] = 1; for(int i = 2; i <= M + 1; i++) inv[i] = mul((mod - mod / i), inv[mod % i]); 
    for(int i = 1; i <= M; i++) {
        int x = read(), y = read();
        v[x].push_back(y); inder[y]++;
    }
    int ans = 1; inder[Y]++; 
    for(int i = 2; i <= N; i++) ans = mul(ans, inder[i]); 
    if(Y == 1) {cout << ans; return 0;}
    memcpy(t, inder, sizeof(inder));
    inder[Y]--;
    f[Y] = ans; Topsort();
    cout << (ans - f[X] + mod) % mod;
    return 0;
}

Posted by valshooter on Sat, 07 Dec 2019 09:56:30 -0800