zoukankan      html  css  js  c++  java
  • 生成最小树(普里姆算法)

    普利姆算法生成最小树,

    当两个节点之间没有边时,权值为65535,结点与自身之间为0.。。。

    #define MAXSIZE 10
    
    typedef struct Graph
    {
        int table[MAXSIZE][MAXSIZE];
        int num;
    }Graph;
    
    void createTable(Graph *graph);
    void printTable(Graph *graph); 
    void prim(Graph *graph);
     
    int main(int argc, char *argv[])
    {
        Graph graph;
        
        
        createTable(&graph);
        
        printTable(&graph);
        
        prim(&graph); 
        return 0;
    }
    
    void prim(Graph *graph) 
    {
        int num = graph->num;
        int pre[num];
        int weight[num];
        int i, j,min, k;
        
        j = 0; 
        
        for(i=0; i<num-1; i++)
        {
            pre[i] = 0;
            weight[i] =( graph->table)[j][i];
        }
        
        for(i=0; i<num; i++)
        {
            min = 65535;
            
            for(j=0;j<num; j++)
            {
                if(weight[j] != 0 && weight[j] < min)
                {
                    min = weight[j];
                    k = j;
                }
            }
            printf("(%d, %d) ", pre[k], k);
            weight[k] = 0;
            
            for(j=0; j<num; j++)
            {
                if(weight[j] != 0 && (graph->table)[k][j] < weight[j] )
                {
                    weight[j] = (graph->table)[k][j];
                    pre[j] = k;
                }
            }
        }
        
    }
    
    void createTable(Graph *graph)
    {
        int i, j, temp;
        printf("输入节点数:");
        scanf("%d", &(graph->num));
        
        for(i=0; i<graph->num; i++)
        {
            for(j=0; j<graph->num; j++)
            {
                scanf("%d", &temp);
                if(temp == ' ')
                {
                    j --;
                }else {
                    (graph->table)[i][j] = temp;
                }
            }
            getchar();
        }
    }
    
    void printTable(Graph *graph)
    {
        int i,j;
        
        for(i=0; i<graph->num; i++)
        {
            for(j=0; j<graph->num; j++)
            {
                printf("%d ", (graph->table)[i][j]);
            }
            printf("
    ");
        }
     }
  • 相关阅读:
    mmdetection安装问题(nms is not compiled with GPU support)
    【洛谷日报#75】浅谈C++指针
    NOIP专题复习3 图论-强连通分量
    NOIP专题复习2 图论-生成树
    NOIP专题复习1 图论-最短路
    题解 P1967 货车运输
    【转】linux expoll模型
    spring mvc 4.1支持protobuf converters
    ubuntu install jdk
    nosql理论基础
  • 原文地址:https://www.cnblogs.com/buerr/p/7492078.html
Copyright © 2011-2022 走看看