国王的烦恼

题意

n 个点 m 条边,每条边有一个权值表示该边消失的时间,求有新的点不联通的时刻的数量。

题解

以时间从大到小排序,用并查集反向建图,注意同时刻只能计一次。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include <bits/stdc++.h>
#define forl(i, l, r) for (int i = l; i <= r; i++)
#define forr(i, r, l) for (int i = r; i >= l; i--)
#define for1(i, n) for (int i = 1; i <= n; i++)
#define for0(i, n) for (int i = 0; i < n; i++)
#define meminf(a) memset(a, inf, sizeof(a))
#define mem_1(a) memset(a, -1, sizeof(a))
#define mem0(a) memset(a, 0, sizeof(a))
#define inlld(lld) scanf("%lld", &lld)
#define inlf(f) scanf("%lf", &f)
#define ind(d) scanf("%d", &d)
#define ins(s) scanf("%s", s)
#define mp make_pair
#define pb push_back
#define fi first
#define se second
typedef std::pair<long long, long long> pll;
typedef std::vector<long long> vll;
typedef std::pair<int, int> pii;
typedef unsigned long long ull;
typedef std::vector<int> vii;
typedef long double db;
typedef long long ll;
const db pi = acos((db)-1);
const ll inf =0x3f3f3f3f;
const ll mod = 1e9+7;
const int N = 1.1e4;
const db eps = 1e-8;
using namespace std;
int sign(db a) { return a < -eps ? -1 : a > eps; }
int db_cmp(db a, db b){ return sign(a-b); }

int uni[N];
int find_r(int x){
if(uni[x]==x)return x;
else return uni[x]=find_r(uni[x]);
}
bool merge(int a,int b){
int fa=find_r(a),fb=find_r(b);
if(fa==fb)return 0;
uni[fa]=fb;
return 1;
}
struct edg{
int u,v,w;
bool operator < (const edg y)const{
return w>y.w;
}
}edge[10*N];
int main() {
#ifdef PerpEternal
// freopen("/Users/perpeternal/Documents/Sketch/data/in.dat", "r", stdin);
// freopen("/Users/perpeternal/Documents/Sketch/data/out.dat", "w", stdout);
#endif
//ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
int n,m;
scanf("%d%d",&n,&m);
for1(i,n)uni[i]=i;
for0(i,m)scanf("%d%d%d",&edge[i].u,&edge[i].v,&edge[i].w);
sort(edge,edge+m);
int ans=0,time=0;
for0(i,m){
// cout<<edge[i].u<<' '<<edge[i].v<<' '<<edge[i].w<<endl;
if(merge(edge[i].u,edge[i].v)){
if(edge[i].w!=time){
time=edge[i].w;
ans++;
}
}
}
printf("%d\n",ans);
return 0;
}