*********(北大)最小生成树总结+习题 (Prime and Kruskal)*********

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/LMengi000/article/details/81985617

目录

简述:Prime and Kruskal

HDU 1301 Jungle Roads

POJ 1258  Agri-Net



简述:Prime and Kruacal

https://blog.csdn.net/luoshixian099/article/details/51908175

Prime: 加点法,适合稠密图,每次迭代选择代价最小的边对应的点,加入到最小生成树中。算法从某一个顶点s开始,逐渐长大覆盖整个连通网的所有顶点。

  • 图的所有顶点集合为V;初始令集合u={s},v=V−u;
  • 在两个集合u,v能够组成的边中,选择一条代价最小的边(u0,v0),加入到最小生成树中,并把v0v0并入到集合u中。
  • 重复上述步骤,直到最小生成树有n-1条边或者n个顶点为止。

1.Prime算法的构造过程:

  1. 首先将初始定点u加入U中,对其余的每一个顶点vj,将closedge[j]均初始化为到u的边信息。
  2. 循环n-1次,做如下处理:
  •   从各组边closedge中选择最小边closedge[k];
  • 将k加入到U中
  • 更新剩余的每组最小边信息closedge[j],新增加了一条从k到j的边,如果更新的权值比closedge[j]的权值小,则将closedge[j]更新为新边的权值。

Kruscal:加边法,适合稀疏图,初始最小生成树边数为0,每迭代一次就选择一条满足条件的最小代价边,加入到最小生成树的边集合里。 

2.Kruscal算法的构造过程:

 把图中的所有边按代价从小到大排序; 
2. 把图中的n个顶点看成独立的n棵树组成的森林; 
3. 按权值从小到大选择边,所选的边连接的两个顶点ui,vi,应属于两颗不同的树,则成为最小生成树的一条边,并将这两颗树合并作为一颗树。 
4. 重复(3),直到所有顶点都在一颗树内或者有n-1条边为止。

可以用并查集来实现, 

HDU 1301 Jungle Roads

 

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 10073    Accepted Submission(s): 7378


 

Problem Description


The Head Elder of the tropical island of Lagrishan has a problem. A burst of foreign aid money was spent on extra roads between villages some years ago. But the jungle overtakes roads relentlessly, so the large road network is too expensive to maintain. The Council of Elders must choose to stop maintaining some roads. The map above on the left shows all the roads in use now and the cost in aacms per month to maintain them. Of course there needs to be some way to get between all the villages on maintained roads, even if the route is not as short as before. The Chief Elder would like to tell the Council of Elders what would be the smallest amount they could spend in aacms per month to maintain roads that would connect all the villages. The villages are labeled A through I in the maps above. The map on the right shows the roads that could be maintained most cheaply, for 216 aacms per month. Your task is to write a program that will solve such problems.

The input consists of one to 100 data sets, followed by a final line containing only 0. Each data set starts with a line containing only a number n, which is the number of villages, 1 < n < 27, and the villages are labeled with the first n letters of the alphabet, capitalized. Each data set is completed with n-1 lines that start with village labels in alphabetical order. There is no line for the last village. Each line for a village starts with the village label followed by a number, k, of roads from this village to villages with labels later in the alphabet. If k is greater than 0, the line continues with data for each of the k roads. The data for each road is the village label for the other end of the road followed by the monthly maintenance cost in aacms for the road. Maintenance costs will be positive integers less than 100. All data fields in the row are separated by single blanks. The road network will always allow travel between all the villages. The network will never have more than 75 roads. No village will have more than 15 roads going to other villages (before or after in the alphabet). In the sample input below, the first data set goes with the map above.

The output is one integer per line for each data set: the minimum cost in aacms per month to maintain a road system that connect all the villages. Caution: A brute force solution that examines every possible set of roads will not finish within the one minute time limit.  

Sample Input

 

9 A 2 B 12 I 25 B 3 C 10 H 40 I 8 C 2 D 18 G 55 D 1 E 44 E 2 F 60 G 38 F 0 G 1 H 35 H 1 I 35 3 A 2 B 10 C 40 B 1 C 20 0

 

Sample Output

 

216 30

 

Source

Mid-Central USA 2002

 

Recommend

Eddy   |   We have carefully selected several similar problems for you:  1162 1102 1233 1217 1142 

 

Statistic | Submit | Discuss | Note

Prime算法:

#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<algorithm>
#include<vector>
#include<math.h>
#include<string.h>
using namespace std;
const int INF=1<<30;
int map[27][27];
int d[27];
int vis[27];
int main()
{
	int k,n,m,minn,temp,sum;
	char ch;
	while(scanf("%d",&n)&& n)
	{
		getchar();
		memset(d,0,sizeof(d));
		memset(vis,true,sizeof(vis));
		memset(map,0x1f,sizeof(map));
		for(int i=1;i<n;i++)
		{	
		    getchar();//注意要加这一句,读入回车符  不然回车符就会被ch读走 
		    scanf("%c",&ch);
		    scanf("%d",&m);
			for(int j=1;j<=m;j++)
		   {
			    scanf("%c",&ch);
			   // getchar();
		    	scanf("%c",&ch);
			    scanf("%d",&temp);
			    map[i-1][ch-'A']=temp;
			    map[ch-'A'][i-1]=temp;
		   }
		}
		for(int i=1;i<n;i++)
		  d[i]=map[i][0];
		 sum=0;
		 vis[0]=false;
		 for(int i=1;i<n;i++)
		 {
		 	minn=INF;
		 	for(int j=0;j<n;j++)
		 		if(vis[j] && d[j]<minn)
		 		{
		 		    minn=d[j];
					 temp=j;	
				}
				vis[temp]=false;
				sum+=minn;
				for(int j=0;j<n;j++)
				{
					if(vis[j] && d[j]>map[j][temp])
					{
						d[j]=map[j][temp];
					}
				}
		 }
		 cout<<sum<<endl;
	}
	return 0;
}

注意:

1. getchar();//注意要加这一句,读入回车符  不然回车符就会被ch读走 

POJ 1258  Agri-Net

Description

Farmer John has been elected mayor of his town! One of his campaign promises was to bring internet connectivity to all farms in the area. He needs your help, of course. 
Farmer John ordered a high speed connection for his farm and is going to share his connectivity with the other farmers. To minimize cost, he wants to lay the minimum amount of optical fiber to connect his farm to all the other farms. 
Given a list of how much fiber it takes to connect each pair of farms, you must find the minimum amount of fiber needed to connect them all together. Each farm must connect to some other farm such that a packet can flow from any one farm to any other farm. 
The distance between any two farms will not exceed 100,000. 
Input

The input includes several cases. For each case, the first line contains the number of farms, N (3 <= N <= 100). The following lines contain the N x N conectivity matrix, where each element shows the distance from on farm to another. Logically, they are N lines of N space-separated integers. Physically, they are limited in length to 80 characters, so some lines continue onto others. Of course, the diagonal will be 0, since the distance from farm i to itself is not interesting for this problem.
Output

For each case, output a single integer length that is the sum of the minimum length of fiber required to connect the entire set of farms.
Sample Input

4
0 4 9 21
4 0 8 17
9 8 0 16
21 17 16 0
Sample Output

28
Source

USACO 102

Prime:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#include<queue>
#include<math.h>
using namespace std;
const int INF=1<<30;
const int maxn=1000;
int map[maxn][maxn];
int vis[maxn];
int d[maxn];
int n,temp,minn,sum;
int main()
{
	  while(scanf("%d",&n)!=EOF)
	  {
	  	memset(vis,0,sizeof(vis));
	  	memset(map,0x1f,sizeof(map));
		memset(d,0,sizeof(d));
	    for(int i=0;i<n;i++)
		{
		  for(int j=0;j<n;j++)
		  {
		     scanf("%d",&map[i][j]);
		     if(map[i][j]==0)
		     map[i][j]=INF;
		  }	
		}	
           for(int i=1;i<n;i++)	
		    d[i]=map[i][0];
		     sum=0;
		    vis[0]=1; 
		    for(int i=1;i<n;i++)
		    {
		    	minn=INF; //注意:赋值是=,错写成==  
		    	for(int j=0;j<n;j++)
		    	{
		    		if(vis[j]==0 && d[j]<minn)
		    		{
		    			minn=d[j];
		    			temp=j;
				   }		    		
				}
				 sum+=minn;
				 vis[temp]=1;
				 for(int j=0;j<n;j++)
				 	if(vis[j]==0 && d[j]>map[j][temp])
				 	  d[j]=map[j][temp];
			}
			printf("%d\n",sum);
	  }
	  return 0;
}

prioirty_queue实现 Prim + 堆 :

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#include<queue>
#include<vector>
#include<math.h>
using namespace std;
const int INF=1<<30;
struct Edge
{
	int v;
	int w;
	Edge(int v_=0,int w_=INF):v(v_),w(w_){}
	bool operator<(const Edge & f)const
	{
	   return w>f.w;	
	}
};
vector< vector<Edge> >G(110);
int HeaPrime(const vector<vector<Edge> >&G,int n)
{
	int i,j,k;
	Edge xDist(0,0);
	priority_queue<Edge>pq;
	vector<int>vDist(n);
	vector<int>vUsed(n);
	int nDoneNum=0;
	for(int i=0;i<n;i++)
	{
		vUsed[i]=0;
		vDist[i]=INF;
	}
	nDoneNum=0;
	int nTotalW=0;
	pq.push(Edge(0,0));
	while(nDoneNum<n && !pq.empty())
	{
		do
		{
			xDist=pq.top();
			pq.pop();
		}while(vUsed[xDist.v]==1 && !pq.empty());
		if(vUsed[xDist.v]==0)
		{
			nTotalW+=xDist.w;
			vUsed[xDist.v]=1;
			nDoneNum++;
			for(int i=0;i<G[xDist.v].size();i++)
			{
				int k=G[xDist.v][i].v;
				if(vUsed[k]==0)
				{
					int w=G[xDist.v][i].w;
					if(vDist[k]>w)
					{
						vDist[k]=w;
						pq.push(Edge(k,w));
					}
				}
			}
		}
	}
	if(nDoneNum<n)
	   return -1;
	return nTotalW;
}
int main()
{
  int N;
  while(scanf("%d",&N)!=EOF)
  {
  	for(int i=0;i<N;i++)
  	  G[i].clear();
  	for(int i=0;i<N;i++)
  	{
  	  for(int j=0;j<N;j++)
      {
           int w;
		   scanf("%d",&w);
		   G[i].push_back(Edge(j,w));
	  }	
	}
	printf("%d\n",HeaPrime(G,N));
  } 
  return 0;	
}

注意: 

最近写代码很是马虎,一些不应该错的细节问题总是出错,这样很浪费时间,前几天是基本for循环写错,今天是基本输入写错,竟然多输入了一个数字;今天下午把赋值的=,写成了==,改了好半天,做这个Prime的时候,连续输入的!=EOF

又忘了加,导致不断超时,这样改来改去浪费了好多时间,很是心累。最近状态不断下滑,学习效率有保证但是心里觉得超级累啊。

 Kruskal:

f 0 1 2 3 4
0 1 2 3 4
a 0 1 2 3 4 5 6 7 8 9 10 11
x 0 0 0 1 1 1 2 2 2 3 3 3
y 1 2 3 0 2 3 0 1 3 0 1 2
w 4 9 21 4 8 17 9 8 16 21 17

16 

把边的权值从小到大排序,排序之后就循环判断边的两个端点是否在同一个集合中,如果不在同一个集合中,就把两端点加入同一个集合,并且用ans来累加计算权值,最后算出的权值就是最小的代码值。

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#include<queue>
#include<vector>
#include<math.h>
using namespace std;
struct Node
{
	int x,y,w;
	bool operator<(const Node & t)const
	{
		return w<t.w;
	}
}a[10002];
int f[102];
int find(int x)
{
	if(f[x]==x)
	 return x;
	 return f[x]=find(f[x]);
}
bool compare(struct Node a,struct Node b)
{
	return a.w<b.w;
}
int main()
{
  int n,w;
  while(scanf("%d",&n)!=EOF)	
  {
  	for(int i=0;i<=n;i++)
  	   f[i]=i;
  	int m=0,ans=0;
  	for(int i=0;i<n;i++)
  	{
  	  for(int j=0;j<n;j++)
		{
		   scanf("%d",&w);
		   if(i!=j)
		    a[m].x=i,a[m].y=j,a[m++].w=w;	
		}	
	}
/*	for(int i=0;i<m;i++)
	{
			printf("a[%d].x=%d a[%d].y=%d  a[%d].w=%d \n",i,a[i].x,i,a[i].y,i,a[i].w);
	}*/
	sort(a,a+m,compare);
	int num=0;
	for(int i=0;i<m;i++)
	{
		if(find(a[i].x)!=find(a[i].y))
		{
			f[find(a[i].x)]=f[find(a[i].y)];
			ans+=a[i].w;
			if(++num==n-1)
			break;
		}
	}
	printf("%d\n",ans);
  }
  return 0;
}
 /*
4
0 4 9 21
4 0 8 17
9 8 0 16
21 17 16 0
*/

猜你喜欢

转载自blog.csdn.net/LMengi000/article/details/81985617