https://www.luogu.com.cn/problemnew/solution/P4208
看这里的题解就够了其实
#include<iostream> #include<cstdio> #include<cstring> #include<vector> #include<algorithm> #define maxn 1010 using namespace std; const int mod = 31011; int n, m; struct Node { int be, en, len, cnt; }que[maxn]; vector<Node>ins; bool bml(Node a, Node b) { return a.len < b.len; } int par[111]; int find(int x) { if (par[x] == -1) return x; return find(par[x]); } int ans = 0; int dfs(int x, int i, int k) { if (i == ins[x].en + 1) { if (k == ins[x].cnt) ans++; return 0; } int a = find(que[i].be); int b = find(que[i].en); if (a != b) { par[a] = b; dfs(x, i + 1, k + 1);//选 par[a] = -1; par[b] = -1; } dfs(x, i + 1, k);//不选 } int main() { memset(par, -1, sizeof(par)); scanf("%d%d", &n, &m); for (int i = 1; i <= m; i++) { scanf("%d%d%d", &que[i].be, &que[i].en, &que[i].len); } sort(que + 1, que + m + 1, bml); que[m + 1].len = -1; int cnt = 0; int nn = 0; for (int i = 1; i <= m; i++) { int a = find(que[i].be); int b = find(que[i].en); if (a != b) { par[a] = b; cnt++; nn++; } if (que[i].len != que[i+1].len) { Node an; an.en = i; an.len = que[i].len; an.cnt = cnt; cnt = 0; if (ins.size() == 0) an.be = 1; else an.be = ins[ins.size() - 1].en + 1; ins.push_back(an); } } if (nn != n - 1) { printf("0\n"); return 0; } memset(par, -1, sizeof(par)); int cns = 1; for (int i = 0; i < ins.size(); i++) { dfs(i, ins[i].be, 0); cns = (cns*ans) % mod; ans = 0; for (int j = ins[i].be; j <= ins[i].en; j++) { int a = find(que[j].be); int b = find(que[j].en); if (a != b) { par[a] = b; } } } printf("%d\n", cns); return 0; }