牛客OI周赛4-提高组 A K小生成树(kmst)

时间:2024-05-25 15:35:14

K小生成树(kmst)

思路:

暴力+并查集

枚举边的子集,用并查集判断两个点联不联通

代码:

#include<bits/stdc++.h>
using namespace std;
#define fi first
#define se second
#define pi acos(-1.0)
#define LL long long
//#define mp make_pair
#define pb push_back
#define ls rt<<1, l, m
#define rs rt<<1|1, m+1, r
#define ULL unsigned LL
#define pll pair<LL, LL>
#define pli pair<LL, int>
#define pii pair<int, int>
#define piii pair<pii, int>
#define mem(a, b) memset(a, b, sizeof(a))
#define fio ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define fopen freopen("in.txt", "r", stdin);freopen("out.txt", "w", stout);
//head const int N = ;
piii e[N];
int fa[N], tmp[(<<) + ];
int n, m, top = ;
int Find(int x) {
if(x == fa[x]) return x;
else return Find(fa[x]);
}
void dfs(int i, int cnt, int len) {
if(m-i+ + cnt < n-) return ;//这个剪枝很优秀
if(i == m+) {
if(cnt == n-) tmp[++top] = len;
return ;
}
dfs(i+, cnt, len);
int u = Find(e[i].fi.fi), v = Find(e[i].fi.se);
if(u != v) {
fa[u] = v;
dfs(i+, cnt+, len+e[i].se);
fa[u] = u;
}
}
int main() {
int l, r, q;
scanf("%d %d", &n, &m);
for (int i = ; i <= m; i++) {
scanf("%d %d %d", &e[i].fi.fi, &e[i].fi.se, &e[i].se);
}
for (int i = ; i <= n; i++) fa[i] = i;
dfs(, , );
sort(tmp+, tmp++top);
scanf("%d", &q);
while(q--) {
scanf("%d %d", &l, &r);
printf("%d\n", upper_bound(tmp+, tmp++top, r) - lower_bound(tmp+, tmp++top, l));
}
return ;
}