水最小生成树 测试下模板 直接贴代码了
prim算法的
#include <iostream>
#include <cstring>
#include <string>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <vector>
#include <queue>
#include <map>
#include<set>
#include<stack>
#define bug puts("bugbugbug");
using namespace std;
typedef long long ll;
//适合稠密图 复杂度n*n n为点数
const int INF=1000000010;
const int N=105;//N 为点的数量
int vis[N],dis[N];
vector<int> V[N];//邻接表存边
int g[N][N]={0};//邻接矩阵存边
int n,m;
int prim() {
memset(vis, 0,sizeof(vis));
for (int i = 1; i <= n; i++) dis[i] = i==1? 0 : INF;//初始化
int ans = 0;
int i;
for (i = 1; i <= n; i++) {
int k = -1, minn = INF;
for (int j = 1; j <= n; j++)
if (!vis[j] && dis[j] < minn) {
minn = dis[j];
k = j;
}
if (k == -1) break;
vis[k] = 1, ans += dis[k];
for (int j = 0; j < V[k].size(); j++) {
int u = V[k][j];
if (!vis[u] && g[k][u] < dis[u]) dis[u] = g[k][u];
}
}
if(i!=n+1)return -1;
return ans;
}
int main()
{
while(~scanf("%d%d",&m,&n)&&m)
{
for(int i=0;i<=n;i++)
V[i].clear();
memset(g,0,sizeof(g));
for(int i=0;i<m;i++){
int a,b,c;
scanf("%d%d%d",&a,&b,&c);
V[a].push_back(b);
V[b].push_back(a);
g[a][b]=g[b][a]=c;
}
int ans=prim();
if(ans==-1) puts("?");
else printf("%d\n",ans);
}
}
Kruscal的
#include <iostream>
#include <cstring>
#include <string>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <vector>
#include <queue>
#include <map>
#include<set>
#include<stack>
#define bug puts("bugbugbug");
using namespace std;
typedef long long ll;
const int maxm=10005;
int f[105];
int n,m;
struct node
{
int x, y, v;
bool operator<(const node &b)const{
if(this->v!=b.v)
return (this->v<b.v);
if(this->x!=b.x)
return (this->x<b.x);
return (this->y<b.y);
}
} e[maxm];
int find(int x){ return f[x]= f[x]==x?x:find(f[x]); }
int Kruscal()
{
sort(e, e + m);
int cnt = n, ans = 0;
for(int i = 0; i < n; i++) f[i] = i;
for (int i = 0; i < m; i++)
{
int x = find(e[i].x);
int y = find(e[i].y);
if (x != y)
{
f[x] = y;
cnt--;
ans += e[i].v;
if (cnt == 1) break;
}
}
if(cnt!=1)return -1;
return ans;
}
int main()
{
while(~scanf("%d%d",&m,&n)&&m)
{
for(int i=0;i<m;i++)
scanf("%d%d%d",&e[i].x,&e[i].y,&e[i].v);
int ans=Kruscal();
if(ans==-1) puts("?");
else printf("%d\n",ans);
}
}