程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> 關於C語言 >> 純C語言:貪心Kruskal算法生成樹源碼

純C語言:貪心Kruskal算法生成樹源碼

編輯:關於C語言

#include 
#define Max 100

typedef struct{
         int u;
		 int v;
		 int weight;
}edge;
edge edges[Max];
int nodes[Max];
void interchange(edge* m,edge* n)
{
	edge temp=*m;
	*m=*n;
	*n=temp;

}
int partition(edge array[],int p,int q)
{
	int i,j;
	i=p;
	j=q+1;
	while(1)
	{
		do i++;
		while((array[i].weightarray[p].weight)&&(j!=p));
		if(i>nodenum>>edgenum;
        cout<<"請輸入每條邊的起點、終點及權值:"<>edges[i].u>>edges[i].v>>edges[i].weight;
			 
        }
		for(i=1;i<=nodenum;i++)
			nodes[i]=0;
        quicksort(edges,0,edgenum-1);
        for(i = 0; i < edgenum ; i++)
		{               
                m = edges[i].u;
                n = edges[i].v;
                safe = 0;
                if(nodes[m] == 0 &&nodes[n] == 0){
                        nodes[m] = flag;
						 nodes[n] =flag;
						 flag++;
                        safe = 1;//a safe edge

                }
				else
				{
					if(nodes[m] == 0 ||nodes[n] == 0 )
					{
				    	if(nodes[m] == 0 )                        
					        nodes[m] = nodes[n];
				      	else nodes[n]=nodes[m];
				        
                        safe = 1;//a safe edge
					}
					else 
						if(nodes[m] != nodes[n])
						{					
                              for(j = 1; j <= nodenum; j++)
							  {
                                if((nodes[j] == nodes[m] || nodes[j] == nodes[n])&&(j!=m&&j!=n))
								{
                                        nodes[j] = flag;
                                }
							  }  
							  nodes[m]=flag;
							  nodes[n]=flag;
							  flag++;                          
                              safe = 1;//a safe edge

						}

                }
				 
                if(safe == 1){//reserve a safe edge

                        edges[presult].u = m;
                        edges[presult].v = n;
                        edges[presult].weight = edges[i].weight;
                        presult++;
                }
       
              if(presult == nodenum-1 ){//found mst

                        break;
                } 
		}
        cout<<"Print the result:"<

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved