H - Boboniu Walks on Graph
https://codeforces.com/problemset/problem/1394/B
题意
给n个点m条有向边,么个点的出度不超过k(k<=9),每条边都有一个边权在(\(1<=w<=m\))且每条边权都不相同,
求有多少个k元组(c1,c2,c3,..ck)满足对于某个点,出度为x,则它的所有出边中,只能走边权第\(c_x\)大的边,然后每个点都能从自己出发走回自己。
思路
不难发现,要满足所有点都能走回自己,那必然是一个有向环。
因为k很小,我们可以暴力枚举所有情况,复杂度为k!.
为了快速check是否满足条件,我们用hash,每个点给一个点权,比对点权和来判断是否满足条件,复杂度变成了\(O(nk!)\)
这样任然超时,可以再做个预处理,将出度为i,选择走第j条边的所有边累加给 sum[i][j],后续就可以o(1)地加答案了。
复杂度变成了O(k * k!)
#include<bits/stdc++.h>
#include<array>
#define ll long long
#define all(a) a.begin(),a.end()
using namespace std;
const int N = 2e5 + 5;
const int M = 1e6 + 1;
const ll INF = 0x3f3f3f3f3f3f3f3f;
const int inf = 0x3f3f3f3f;
const ll mod = 1e9 + 7;
#define int ll
int n, m, k, tot, cnt;
int bs = 131, base[N], out[N], sum[10][10], c[10];
vector<pair<int, int>>g[N];
void check() {
int temp = 0;
for (int i = 1; i <= k; i++) {
temp = (temp + sum[i][c[i]]) % mod;
}
if (temp == tot) cnt++;
}
void dfs(int x, int ans) {
if (x > k) {
if (ans == tot) cnt++;
}
else {
for (int i = 1; i <= x; i++) {
dfs(x + 1, (ans + sum[x][i]) % mod);
}
}
}
void solve() {
cin >> n >> m >> k;
base[0] = 1;
for (int i = 1; i <= n; i++) {
base[i] = (base[i - 1] * bs) % mod;
tot = (tot + base[i]) % mod;
}
for (int i = 1, u, v, w; i <= m; i++) {
cin >> u >> v >> w;
g[u].push_back({ w, v });
out[u]++;
}
for (int i = 1; i <= n; i++)
sort(g[i].begin(), g[i].end());
//预处理
for (int i = 1; i <= n; i++) {
for (int j = 0; j < out[i]; j++) {
sum[out[i]][j + 1] = (sum[out[i]][j + 1] + base[g[i][j].second]) % mod;
}
}
dfs(1, 0);
cout << cnt << "\n";
}
signed main()
{
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
int _t = 1;
//cin >> _t;
while (_t--) {
solve();
}
return 0;
}
标签:Training,const,复杂度,int,ll,补题,哈希,出度,define
From: https://www.cnblogs.com/yaqu-qxyq/p/16815611.html