poj2485Highways(最小產生樹)

來源:互聯網
上載者:User

其實我覺得這道題有點像次小產生樹,用了一個max數組,最後把max數組裡的最大值求出來就行了,我之前寫錯是因為我求的是max[0][n-1],以為這樣就能把全圖都包括,得到的就是最大的,然而事實卻並不是這樣,max[0][n-1]表示的是從0到n-1這段路徑的最大邊的長度,然而我們求的是最小產生樹的最大邊,很有可能這條邊是最大的,但是它並不在0到n-1這條路徑上,所以要把所有的max數組遍曆一遍就ok了

#include <iostream>#include <string.h>#include <stdio.h>using namespace std;const int maxn=1005;const int INF=0x3f3f3f3f;bool vis[maxn];bool used[maxn][maxn];int pre[maxn];int lowc[maxn];int Max[maxn][maxn];int mapp[maxn][maxn];int prim(int cost[][maxn],int n){    int ans=0;    memset(vis,false,sizeof(vis));    memset(Max,0,sizeof(Max));    memset(used,false,sizeof(used));    vis[0]=true;    pre[0]=-1;    for(int i=1; i<n; i++)    {        lowc[i]=cost[0][i];        pre[i]=0;    }    lowc[0]=0;    for(int i=1; i<n; i++)    {        int minc=INF;        int p=-1;        for(int j=0; j<n; j++)            if(!vis[j]&&minc>lowc[j])            {                minc=lowc[j];                p=j;            }//        if(minc==INF)//            return -1;        ans+=minc;        vis[p]=true;        used[p][pre[p]]=used[pre[p]][p]=true;        for(int j=0; j<n; j++)        {            if(vis[j]&&j!=p)                Max[j][p]=Max[p][j]=max(Max[j][pre[p]],lowc[p]);            if(!vis[j]&&lowc[j]>cost[p][j])            {                lowc[j]=cost[p][j];                pre[j]=p;            }        }    }    int sumn=0;    for(int i=0; i<n; i++)        for(int j=0; j<n; j++)            sumn=max(sumn,Max[i][j]);    return sumn;}int main(){    //freopen("cin.txt","r",stdin);   // freopen("cout.txt","w",stdout);    int T,n,s;    ios::sync_with_stdio(false);    while(cin>>T)    {        while(T--)        {            cin>>n;            for(int i=0; i<n; i++)            {                for(int j=0; j<n; j++)                {                    if(i==j)                        mapp[i][j]=0;                    else mapp[i][j]=INF;                }            }            for(int i=0; i<n; i++)            {                for(int j=0; j<n; j++)                {                    cin>>s;                    mapp[i][j]=min(mapp[i][j],s);                }            }            int sum=prim(mapp,n);            cout<<sum<<endl;        }    }    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.