zoukankan      html  css  js  c++  java
  • hdu 3371 Connect the Cities(最小生成树)

    题目:http://acm.hdu.edu.cn/showproblem.php?pid=3371

    984ms风险飘过~~~

    /************************************************************************/
    /*     
            hdu  Connect the Cities
            最小生成树
            题目大意:最小生成树,题目很长,题意很简单就是最小生成树。关键是构建图
    */
    /************************************************************************/
    
    #include <stdio.h>
    #include <string.h>
    #include <algorithm>
    #include <math.h>
    
    #define MAX 0xfffffff
    
    const int N = 501;
    int map[N][N];
    int vis[N];
    int mark[N];
    int num,n;
    
    void build_map()
    {
        int m,k;
        int q,p,c;
        int t;
    
        scanf("%d%d%d",&n,&m,&k);
        for (int i = 1; i <= n; i++)
        for (int j = i; j <= n; j++)
        map[i][j] = map[j][i] = ((i==j)?0:MAX);
    
        for (int i = 0; i < m; i++)
        {
            scanf("%d%d%d",&p,&q,&c);
            if (map[p][q] > c)
            {
                map[p][q] = map[q][p] = c;
            }
            
        }
        while(k--)
        {
            scanf("%d",&t);
            for (int i = 0; i < t; i++)
            {
                scanf("%d",&mark[i]);
                for (int j = 0; j < i; j++)
                {
                    map[mark[j]][mark[i]] = map[mark[i]][mark[j]] = 0;
                }
            }
        }
    }
    
    int prim()
    {
        int t = n;
        int sum = 0;
        int min,k;
        vis[0] = 1;
        while(--t)
        {
            min = MAX;
            for(int i = 2; i <= n; i++)
            {
                if (vis[i] != 1 && map[1][i] < min)
                {
                    min = map[1][i];
                    k = i;
                }
            }
            if(min == MAX)break;
            vis[k] = 1;
            sum += min;
            for (int i = 2; i <= n; i++)
            {
                if (vis[i] != 1 && map[k][i] < map[1][i])
                map[1][i] = map[k][i];
            }
        }
        return t==0?sum:-1;
    }
    
    
    int main()
    {
        scanf("%d",&num);
        while(num--)
        {
            build_map();
            memset(vis,0,sizeof(vis));
            printf("%d
    ",prim());
        }
        return 0;
    }
  • 相关阅读:
    调试php的soapCient
    thinkphp 常见问题
    git使用备忘
    org.apache.catalina.startup.Catalina异常处理
    Java多线程中join方法详解
    WebSphere 安装和配置过程
    数据库错误
    把sql输出成。sql文件
    Oracle 使用命令导入dmp文件
    pl_sql develope连接远程数据库的方法
  • 原文地址:https://www.cnblogs.com/newpanderking/p/3253094.html
Copyright © 2011-2022 走看看