[关闭]
@ZCDHJ 2019-08-16T02:32:34.000000Z 字数 1390 阅读 815

JSOI2008 最小生成树计数

未分类


首先考虑 Kruskal 算法的过程,实际上是将边权升序排序后全部加入最小生成树再去掉所有的环,所以对于每种不同的最小生成树每种边权的数量都是一定的,同时也可以发现在加入一种新的边权后联通块的情况都是一模一样的,因为同种边权数量不超过 ,所以直接爆搜每种边权选哪几个,再乘起来,中途使用不路径压缩的并查集(为了方便 DFS 的撤销

  1. #include <iostream>
  2. #include <cstdio>
  3. #include <algorithm>
  4. const int MAXN = 100;
  5. const int MAXM = 10000;
  6. const int MOD = 31011;
  7. int n, m, cnt, res;
  8. int L[MAXM | 1], R[MAXM | 1], sum[MAXM | 1], fset[MAXN | 1];
  9. struct Edge {
  10. int from, to, w;
  11. Edge() : from(0), to(0), w(0) {}
  12. friend bool operator< (const Edge &lhs, const Edge &rhs) {
  13. return lhs.w < rhs.w;
  14. }
  15. } e[MAXM | 1];
  16. inline int read() {
  17. register int x = 0;
  18. register char ch = getchar();
  19. while (!isdigit(ch)) ch = getchar();
  20. while (isdigit(ch)) {
  21. x = x * 10 + ch - '0';
  22. ch = getchar();
  23. }
  24. return x;
  25. }
  26. int f(int x) {
  27. return fset[x] == x ? x : f(fset[x]);
  28. }
  29. void dfs(int x, int id, int tot) {
  30. if (x == R[id] + 1) {
  31. if (tot == sum[id]) ++res;
  32. return;
  33. }
  34. int from = f(e[x].from), to = f(e[x].to);
  35. if (from != to) {
  36. fset[from] = to;
  37. dfs(x + 1, id, tot + 1);
  38. fset[from] = from;
  39. }
  40. dfs(x + 1, id, tot);
  41. }
  42. int main() {
  43. n = read();
  44. m = read();
  45. for (int i = 1; i <= m; ++i) {
  46. e[i].from = read();
  47. e[i].to = read();
  48. e[i].w = read();
  49. }
  50. std::sort(e + 1, e + 1 + m);
  51. for (int i = 1; i <= n; ++i) fset[i] = i;
  52. int ans = 0;
  53. for (int i = 1, j = 0; i <= m; ++i) {
  54. if (e[i].w != e[i - 1].w) {
  55. R[cnt] = i - 1;
  56. L[++cnt] = i;
  57. }
  58. int x = f(e[i].from), y = f(e[i].to);
  59. if (x != y) {
  60. fset[x] = y;
  61. ++sum[cnt];
  62. ++j;
  63. }
  64. if (i == m && j != n - 1) {
  65. puts("0");
  66. return 0;
  67. }
  68. }
  69. R[cnt] = m;
  70. ans = 1;
  71. for (int i = 1; i <= n; ++i) fset[i] = i;
  72. for (int i = 1; i <= cnt; ++i) {
  73. res = 0;
  74. dfs(L[i], i, 0);
  75. ans = ans * res % MOD;
  76. for (int j = L[i]; j <= R[i]; ++j) {
  77. int x = f(e[j].from), y = f(e[j].to);
  78. if (x != y) fset[x] = y;
  79. }
  80. }
  81. printf("%d\n", ans);
  82. return 0;
  83. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注