Problem:
给了一个矩阵,求这个矩阵的最小生成树。
Solution:
密集图利用prim算法。
#include<cstdio>
#include<iostream>
#include<sstream>
#include<cstdlib>
#include<cmath>
#include<cctype>
#include<string>
#include<cstring>
#include<algorithm>
#include<stack>
#include<queue>
#include<set>
#include<map>
#include<ctime>
#include<vector>
#include<fstream>
#include<list>
using namespace std;
#define ms(s) memset(s,0,sizeof(s))
typedef unsigned long long ULL;
typedef long long LL;
const double PI = 3.141592653589;
const int INF = 0x3fffffff;
const int maxn = 105;
int G[maxn][maxn];
bool vis[maxn];
int prim(int n){//index from 1
int mins, vtx, weight = 0;
memset(vis, 0, sizeof(vis));
vis[1] = true;
for(int i = 2; i <= n; ++i){
mins = INF;
for(int j = 1; j <= n; ++j){
if(!vis[j] && G[1][j]<mins){
mins = G[1][j];
vtx = j;
}
}
weight += mins;
vis[vtx] = true;
for(int j = 1; j <= n; ++j){
if(!vis[j] && G[vtx][j]<G[1][j]){
G[1][j] = G[vtx][j];
}
}
}
return weight;
}
int main(){
// freopen("E:\\input.txt","r",stdin);
// freopen("/home/really/Document/output","w",stdout);
// ios::sync_with_stdio(false);
int n;
int ans;
while(~scanf("%d",&n)){
ans = 0;
for(int i = 1; i <= n; ++i){
for(int j = 1; j <= n; ++j){
scanf("%d",&G[i][j]);
}
}
ans = prim(n);
printf("%d\n",ans);
}
return 0;
}
//Kruskal
#include<cstdio>
#include<iostream>
#include<sstream>
#include<cstdlib>
#include<cmath>
#include<cctype>
#include<string>
#include<cstring>
#include<algorithm>
#include<stack>
#include<queue>
#include<set>
#include<map>
#include<ctime>
#include<vector>
#include<fstream>
#include<list>
using namespace std;
#define ms(s) memset(s,0,sizeof(s))
typedef unsigned long long ULL;
typedef long long LL;
const double PI = 3.141592653589;
const int INF = 0x3fffffff;
const int maxn = 110;
struct Edge{
int s, e, w;
Edge(int ns, int ne, int nw) : s(ns), e(ne), w(nw){}
Edge(){}
bool operator < (const Edge& rhs) const{
return w < rhs.w;
}
};
int par[maxn];
void init_par(int n){
for(int i = 0; i <= n; ++i)
par[i] = i;
}
int getPar(int v){
if(par[v] != v)
par[v] = getPar(par[v]);
return par[v];
}
void merges(int a, int b){
par[getPar(a)] = getPar(b);
}
vector<Edge> edges;
int kruskal(int n){
int num = 1, ans = 0;
init_par(n);
sort(edges.begin(), edges.end());
for(int i = 0; i < edges.size(); ++i){
if(getPar(edges[i].s) != getPar(edges[i].e)){
merges(edges[i].s, edges[i].e);
++num; ans += edges[i].w;
}
if(num == n) break;
}
return ans;
}
int main(){
// freopen("E:\\input.txt","r",stdin);
// freopen("/home/really/Document/output","w",stdout);
// ios::sync_with_stdio(false);
int n, ans, w;
while(~scanf("%d",&n)){
ans = 0; edges.clear();
for(int i = 1; i <= n; ++i){
for(int j = 1; j <= n; ++j){
scanf("%d", &w);
edges.push_back(Edge(i, j, w));
}
}
ans = kruskal(n);
printf("%d\n",ans);
}
return 0;
}