NYOJ 38 布線問題

來源:互聯網
上載者:User

標籤:style   blog   color   io   資料   for   問題   div   

思路:剛學的最小產生樹,順便找個題目做一下~,普裡姆演算法輕鬆ac,沒難度。。下次用kruskal演算法試下

 

 

附上ac碼:

#include <stdio.h>#include <string.h>int e[501][501];//儲存地圖 int h[501];int mintree;int v,l;int prime()//普裡姆演算法 {    int i,j;    int book[501];//判斷迴路用的,book為1的表示已經加入樹節點的樓     int temp;    int count=0;//表示加入樹節點的數量     int dis[501];//更新數組,作為輔助用     int sum = 0;//最小路徑     int flag;     memset(book,0,sizeof(book));    book[1] = 1;    count++;        for(i = 1; i<=v;i++)    {        dis[i] = e[1][i];    }        while(count<v)    {        temp = 99999;        for(j = 1;j<=v;j++)        {            if(book[j]==0&&dis[j]<temp)            {                temp = dis[j];                flag = j;            }                    }        book[flag] = 1;        count++;        sum +=dis[flag];                for(j=1;j<=v;j++)        {            if(book[j]==0&&dis[j]>e[flag][j])                dis[j] = e[flag][j];        }    }        mintree = sum;        return 0 ;}int main(){        //freopen("data.txt","r",stdin);    mintree = 99999;//最後輸出結果      int minl;//外界接電需要的錢     int num;     int i,j,value;//臨時變數     scanf("%d",&num);    while(num--)    {        minl = 99999;                        scanf("%d %d",&v,&l);                //初始化地圖         for(i =1;i<=v;i++)        {            for(j =1;j<=v;j++)            {                if(i==j)                    e[i][j] = 0;                else                    e[i][j] = 99999;            }        }                        //讀入資料         for(int k = 1;k<=l;k++)        {            scanf("%d %d %d",&i,&j,&value);            e[i][j] = value;            e[j][i] = value;        }                 //找出外界接電的最小值         for(i =1;i<=v;i++)        {            scanf("%d",h+i);            minl = minl>h[i]?h[i]:minl;        }        prime();        printf("%d\n",mintree+minl);    }            return 0;}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.