Professor Q develops a new software. The software consists of N
modules which are numbered from 1 to N. The i-th module will be started
up by signal Si. If signal Si is generated multiple times, the i-th
module will also be started multiple times. Two different modules may be
started up by the same signal. During its lifecircle, the i-th module
will generate Ki signals: E1, E2, ..., EKi. These signals may start up
other modules and so on. Fortunately the software is so carefully
designed that there is no loop in the starting chain of modules, which
means eventually all the modules will be stoped. Professor Q generates
some initial signals and want to know how many times each module is
started.
constint MAX = 100001; int T, M, N, S, K; vector<int> init; vector<int> SM[MAX]; // Signal -> Module vector<int> MS[MAX]; // Module -> Signal bool visited[MAX]; vector<int> sorted; int dp[MAX];
voiddfs(int m){ if (visited[m]) return; visited[m] = true; for (int signal : MS[m]) { for (intmodule : SM[signal]) { dfs(module); } } sorted.push_back(m); }
intmain(){ scanf("%d", &T); while (T--) { init.clear(); memset(visited, 0, sizeof(visited)); scanf("%d %d", &N, &M); for (int i = 0; i < M; i++) { scanf("%d", &S); init.push_back(S); } for (auto &v : SM) v.clear(); for (auto &v : MS) v.clear(); for (int i = 0; i < N; i++) { scanf("%d %d", &S, &K); SM[S].push_back(i); for (int j = 0; j < K; j++) { scanf("%d", &S); MS[i].push_back(S); } } sorted.clear(); for (int i = 0; i < N; i++) { dfs(i); } memset(dp, 0, sizeof(dp)); for (int s : init) { for (int m : SM[s]) { dp[m] += 1; } } for (auto it = sorted.rbegin(); it != sorted.rend(); it++) { int m = *it; for (int signal : MS[m]) { for (intmodule : SM[signal]) { dp[module] += dp[m]; if (dp[module] >= 142857) dp[module] -= 142857; } } } for (int i = 0; i < N; i++) printf("%d%c", dp[i], i == N - 1 ? '\n' : ' '); } }