洛谷【图论2-3】最小生成树

目录

  • P3366 最小生成树
  • P2872 建树

P3366 最小生成树

使用邻接表存的Kruscal算法

#include
using namespace std;
const int maxn = 10010;
const int INF = 0x3fffffff;

struct node{
	int v,w;
	node(int vv,int ww){
		v = vv;
		w = ww;
	}
};
int n,m;
vector<node> Adj[maxn];
int d[maxn];
bool vis[maxn]={false};

int prim(){
	fill(d,d+maxn,INF);
	int ans=0; 
	d[1] = 0;
	for(int i = 0;i<n;i++){
		int u =-1,MIN=INF;
		for(int j =1;j<=n;j++){
			if(vis[j]==false &&d[j]<MIN){
				u=j;
				MIN=d[j];
			}
		}
		if(u==-1) return -1;
		vis[u]=true;
		ans += d[u];
		for(int j=0;j<Adj[u].size();j++){
			int v = Adj[u][j].v;
			if(vis[v]==false&&Adj[u][j].w<d[v]){
				d[v] = Adj[u][j].w;
			}
		}
	}
	return ans;
}
int main(){
	scanf("%d %d",&n,&m);
	int x,y,z;
	for(int i =0;i<m;i++){
		scanf("%d%d%d",&x,&y,&z);
		Adj[x].push_back(node(y,z));//注意是无向图
		Adj[y].push_back(node(x,z));
	}
	int ans = prim();
	if(ans != -1)
		cout<<ans<<endl;
	else
		cout<<"orz"<<endl;
	return 0;
} 

P2872 建树

使用Prim算法

#include
using namespace std;
const int maxn = 1000010;
const int INF = 0x3fffffff;

struct node{//存储边 
	int x,y;
	double val;
}a[maxn];
int n,m;
int xx[maxn],yy[maxn];
int father[maxn];//存根节点 
bool cmp(node a,node b){
	if(a.val==b.val) return a.x<b.x;
	else return a.val<b.val;
}
int findFather(int x){
	if(father[x]==x) return x;
	else return father[x]=findFather(father[x]);
}
int main(){
	scanf("%d%d",&n,&m);
	for(int i=1;i<=n;i++){
		scanf("%d%d",&xx[i],&yy[i]);
	}
	int cnt = 0;
	for(int i =1;i<=n;i++) father[i] =i;//初始化
	for(int i=1;i<=n;i++){//枚举将两两存入结构体数组 
		for(int j=i+1;j<=n;j++){
			a[++cnt].x = i;
			a[cnt].y = j;
			a[cnt].val = (double)(sqrt((double)(xx[i]-xx[j])*(xx[i]-xx[j])+(double)(yy[i]-yy[j])*(yy[i]-yy[j])));
		}
	} 
	int A,B;
	for(int i=1;i<=m;i++){
		scanf("%d%d",&A,&B);
		a[++cnt].x = A;
		a[cnt].y = B;
		a[cnt].val = 0.0;
	}
	double ans=0.0;
	int top = 0;
	sort(a+1,a+1+cnt,cmp);//把边排序
	for(int i =1;i<=cnt;i++){
		if(findFather(a[++top].x)!=findFather(a[top].y)){
			ans += a[top].val;
			father[findFather(a[top].x)] = findFather(a[top].y);//合并 
		}
	}
	printf("%.2lf",ans); 
	return 0;
}

你可能感兴趣的:(刷题)