#include<iostream>
#include<string.h>
#include<algorithm>
using namespace std;
const int N = 100010;
int n, m;
int p[N];
struct Edge{
int a, b, w;
bool operator< (const Edge &W)const{
return w < W.w;
}
}edges[N];
int find(int x){
if(p[x] != x) p[x] = find(p[x]);
return p[x];
}
int main(){
scanf("%d%d", &n, &m);
for(int i= 0; i < m; i++){
int a, b, w;
scanf("%d%d%d", &a, &b, &w);
edges[i] = {a, b, w};
}
sort(edges, edges + m);
for(int i = 1; i <=n; i++){
p[i] = i;
}
int res = 0, cnt = 0;
for(int i = 1; i <= n; i ++) {
int a = edges[i].a, b = edges[i].b, w = edges[i].w;
a = find(a), b = find(b);
if(a != b){
res += w;
cnt ++;
}
}
if(cnt < n - 1) puts("impossible");
else printf("%d\n", res);
}
二分图
二分图 (Bipartite Graph),也叫二部图,是指这样一个图:
可以将图中的所有顶点分成两个不相交的集合 U 和 V
使得图中的每一条边都连接一个 U 中的顶点和一个 V 中的顶点
同一集合内的顶点之间没有边相连
简单来说,二分图就是可以用两种颜色给所有顶点染色,使得相邻顶点颜色不同
染色法
cpp复制代码
#include<iostream>
#include<cstring>
using namespace std;
const int N = 1e5 +10, M =2e5 + 10;
int n, m;
int h[N], e[M], ne[M], idx;
int color[N];
void add(int a, int b){
e[idx] = b;
ne[idx] = h[a];
h[a] = idx ++;
}
bool dfs(int u, int c){
color[u] = c;
for(int i = h[u]; i != -1; i = ne[i]){
int j = e[i];
//如果当前没有染过颜色
if(!color[j]){
if(!dfs(j, 3 - c)) return false;
}
else if(color[j] == c) return false;
}
return true;
}
int main(){
scanf("%d%d", &n, &m);
memset(h, -1, sizeof h);
while(m --){
int a, b;
scanf("%d%d", &a, &b);
add(a, b);
add(b, a);
}
bool flag = true;
for(int i = 1; i <= n; i ++){
if(!color[i]){
if(!dfs(i, 1)){
flag = false;
break;
}
}
}
if(flag) puts("Yes");
else puts("No");
}