并查集

img

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
#include<bits/stdc++.h>
using namespace std;

const int maxn=1005;
int fa[maxn];

int f(int x){
if(x==fa[x]){
return x;
}
fa[x]=f(fa[x]);
return fa[x];
}

int main() {
int n,m;
while(cin>>n){
if(n==0){
break;
}
cin>>m;
for(int i=1;i<=n;i++){
fa[i]=i;
}
int sum=0;
for(int i=0;i<m;i++){
int x,y;
cin>>x>>y;
int fx=f(x);
int fy=f(y);
if(fx!=fy){
sum++;
fa[fx]=fy;
}
}
int r=n-sum-1;
cout<<r<<endl;
}
}

最小生成树(克鲁斯凯尔)

img

img

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
#include<bits/stdc++.h>
using namespace std;

const int maxn=105;

struct node{
int u,v,w;
}edge[maxn*maxn];

int cmp(node a,node b){
return a.w<b.w;
}

int fa[maxn];

int f(int x){
if(x==fa[x]) return x;
fa[x]=f(fa[x]);
return fa[x];
}

int main() {
int n,m;
while(cin>>n>>m){
if(n==0) break;
int sum=0,numw=0;
for(int i=0;i<n;i++){
cin>>edge[i].u>>edge[i].v>>edge[i].w;
}
for(int i=1;i<=m;i++){
fa[i]=i;
}
sort(edge,edge+n,cmp);
for(int i=0;i<n;i++){
int fx=f(edge[i].u);
int fy=f(edge[i].v);
if(fx!=fy){
fa[fx]=fy;
sum++;
numw+=edge[i].w;
}
}
if(sum < m - 1) { // 边数不足N-1 → 图不连通,无法生成
printf("?\n");
} else { // 边数足够 → 输出最小总权值
printf("%d\n", numw);
}
}
return 0;
}

最短路径(floyd)

边输入边更新,所以不用结构体记录

img

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
#include<bits/stdc++.h>
using namespace std;

#define INF 0x3f3f3f3f // 定义无穷大(0x3f3f3f3f≈1e9,避免溢出且易重置)
const int maxn=105;
int mpt[maxn][maxn];
int m,n;

void floyd(){
for(int k=1;k<=n;k++){
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
mpt[i][j]=min((mpt[i][k]+mpt[k][j]),mpt[i][j]);
}
}
}
}

int main() {
while(cin>>n>>m){
if(n==0&&m==0){
break;
}
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
if(i==j){
mpt[i][j]=0;
}
else mpt[i][j]=INF;
}
}
for(int i=1;i<=m;i++){
int a,b,c;
cin>>a>>b>>c;
if(c<mpt[a][b]){
mpt[a][b]=c;
mpt[b][a]=c;
}
}
floyd();
cout<<mpt[1][n]<<endl;
}

return 0;
}