Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

此题边权有0的情况,prime邻接矩阵O(n^2)

Posted by lpp001 at 2013-04-25 18:52:37 on Problem 1679
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
#define maxn 105
#define INF 9999999
int edge[maxn][maxn];
int max_value[maxn][maxn];//生成树中任意两个顶点之间路径的最大值
int dis[maxn],link[maxn];
bool visit[maxn],judge[maxn][maxn];//记录生成树中那些边构成
int n,m,ans;
void prime()
{   
    ans=0;
    memset(visit,0,sizeof(visit));
    memset(judge,0,sizeof(judge));
    for(int i=2;i<=n;i++)
    {
        dis[i]=INF;
        link[i]=0;
        if(edge[1][i]!=-1)
         {
            dis[i]=edge[1][i];
            link[i]=1;
        }
    }
    link[1]=0;
    dis[1]=0;
    visit[1]=1;
    for(int i=1;i<n;i++)
    {
        int min=INF;
        int index=-1;
        for(int i=1;i<=n;i++)
        {
            if(!visit[i]&&min>dis[i])
            {
                min=dis[i];
                index=i;
            }
        }
        ans+=min;
        for(int i=1;i<=n;i++)
        {
            if(visit[i])
            {
                max_value[i][index]=max(edge[index][link[index]],max_value[link[index]][i]);
                max_value[index][i]=max_value[i][index];
            }
        }
        judge[index][link[index]]=1;
        judge[link[index]][index]=1;
        visit[index]=1;
        for(int i=1;i<=n;i++)
        {
            if(!visit[i]&&edge[index][i]!=-1)
            {
                if(dis[i]>edge[index][i])
                {
                    dis[i]=edge[index][i];
                    link[i]=index;
                }

            }
        }
    }
}
int main()
{
    int cas;
    scanf("%d",&cas);
    while(cas--)
    {
        memset(edge,-1,sizeof(edge));
        scanf("%d%d",&n,&m);
        for(int i=1;i<=m;i++)
        {
            int a,b,c;
            scanf("%d%d%d",&a,&b,&c);
            if(edge[a][b]==-1||edge[a][b]>c)
            {
                edge[a][b]=c;
                edge[b][a]=c;
            }
        }
        prime();
        bool flag=0;
        for(int i=1;i<=n;i++)
        {
            if(flag)break;
            for(int j=1;j<=n;j++)
            {
                if(edge[i][j]!=-1&&!judge[i][j])
                {
                    if(max_value[i][j]==edge[i][j])
                    {
                        flag=1;
                        break;
                    }
                }
            }
        }
        if(flag)printf("Not Unique!\n");
        else printf("%d\n",ans);
    }
}

Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator