Kruskal算法模板
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std
;
struct node
{
int x
,y
;
int w
;
}a
[110];
int pre
[110];
bool cmp(struct node a
,struct node b
)
{
return a
.w
<b
.w
;
}
int find(int root
)
{
if(root
!=pre
[root
]) root
=find(pre
[root
]);
return pre
[root
];
}
int main()
{
int n
,i
,m
;
while(scanf("%d %d",&n
,&m
),n
)
{
memset(pre
,0,sizeof(pre
));
int sum
=0,num
=0;
for(i
=1;i
<=m
;i
++) scanf("%d%d%d",&a
[i
].x
,&a
[i
].y
,&a
[i
].w
);
sort(a
+1,a
+1+m
,cmp
);
for(i
=1;i
<=n
;i
++) pre
[i
]=i
;
for(i
=1;i
<=m
;i
++)
{
int f1
=find(a
[i
].x
);
int f2
=find(a
[i
].y
);
if(f1
!=f2
)
{
pre
[f1
]=f2
;
sum
+=a
[i
].w
;
num
++;
}
if(num
==n
-1) break;
}
if(num
==n
-1)
printf("%d\n",sum
);
else printf("?\n");
}
return 0;
}
Prim 模板
#include<iostream>
#include<cstdio>
#include<vector>
#include<algorithm>
#include<queue>
#define ll long long
using namespace std
;
struct node
{
int to
,len
;
node(int x
,int y
){to
=x
,len
=y
;}
friend bool operator < (node a
,node b
){
return a
.len
>b
.len
;
}
};
int n
,m
;
priority_queue
<node
>q
;
int ans
=0;
bool vis
[1010];
vector
<node
>v
[1010];
void link(int x
,int y
,int z
){
v
[x
].push_back(node(y
,z
));
v
[y
].push_back(node(x
,z
));
}
int main(){
scanf("%d%d",&n
,&m
);
for(int i
=0; i
<m
; i
++){
int x
,y
,z
;
scanf("%d%d%d",&x
,&y
,&z
);
link(x
,y
,z
);
}
vis
[1]=true;
for(int i
=0; i
<v
[1].size(); i
++)q
.push(node(v
[1][i
].to
,v
[1][i
].len
));
int sum
=1;
while(!q
.empty()){
node t
=q
.top();
q
.pop();
if(vis
[t
.to
])continue;
sum
++;
ans
+=t
.len
;
vis
[t
.to
]=true;
if(sum
==n
)break;
for(int i
=0; i
<v
[t
.to
].size(); i
++)if(!vis
[v
[t
.to
][i
].to
])q
.push(node(v
[t
.to
][i
].to
,v
[t
.to
][i
].len
));
}
if(sum
==n
)printf("%d\n",ans
);
else printf("-1\n");
return 0;
}
模板二: 模板题
#include <iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<cstdlib>
#define MAX 27
#define INF 99999999
using namespace std
;
int N
;
int map
[MAX
][MAX
];
int micost
[MAX
];
int vis
[MAX
];
void Prim()
{
int i
,j
,v
,Min
;
int ans
;
for(i
=1;i
<=N
;i
++)
{
micost
[i
]=map
[1][i
];
vis
[i
]=0;
}
micost
[1]=0;
vis
[1]=1;
ans
=0;
for(i
=2;i
<=N
;i
++)
{
Min
=INF
;
for(j
=2;j
<=N
;j
++)
{
if(!vis
[j
]&&Min
>micost
[j
])
v
=j
,Min
=micost
[j
];
}
vis
[v
]=1;
if(Min
!=INF
)
ans
=ans
+Min
;
for(j
=2;j
<=N
;j
++)
{
if(!vis
[j
]&&micost
[j
]>map
[v
][j
])
micost
[j
]=map
[v
][j
];
}
}
cout
<<ans
<<endl
;
}
int main()
{
int i
,j
,num
,x
,y
,z
;
char a
,b
;
while(cin
>>N
,N
)
{
for(i
=1;i
<=N
;i
++)
for(j
=1;j
<=N
;j
++)
{
if(i
==j
)map
[i
][j
]=0;
else
map
[i
][j
]=INF
;
}
for(i
=1;i
<N
;i
++)
{
cin
>>a
>>num
;
for(j
=1;j
<=num
;j
++){
cin
>>b
>>z
;
x
=a
-64;
y
=b
-64;
map
[x
][y
]=map
[y
][x
]=z
;
}
}
Prim();
}
return 0;
}
转载请注明原文地址:https://blackberry.8miu.com/read-33747.html