码迷,mamicode.com
首页 > 其他好文 > 详细

URAL 1982. Electrification Plan(并查集)

时间:2017-06-07 11:15:11      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:UI   size   ant   cost   lan   isis   output   vertica   can   

题目链接:http://acm.timus.ru/problem.aspx?space=1&num=1982



Some country has n cities. The government has decided to electrify all these cities. At first, power stations in k different cities were built. The other cities should be connected with the power stations via power lines. For any cities ij it is possible to build a power line between them incij roubles. The country is in crisis after a civil war, so the government decided to build only a few power lines. Of course from every city there must be a path along the lines to some city with a power station. Find the minimum possible cost to build all necessary power lines.

Input

The first line contains integers n and k (1 ≤ k ≤ n ≤ 100). The second line contains k different integers that are the numbers of the cities with power stations. The next n lines contain an n × ntable of integers {cij} (0 ≤ cij ≤ 105). It is guaranteed that , cij > 0 for i ≠ jcii = 0.

Output

Output the minimum cost to electrify all the cities.

Sample

input output
4 2
1 4
0 2 4 3
2 0 5 2
4 5 0 1
3 2 1 0
3



题意:

给出一些建有电站的城市,求每一个城市都通电的最小花费。

代码例如以下:

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

const int maxn = 10017;
int father[maxn];
int n;
int flag;
struct node
{
    int x, y;
    int c;
} cc[maxn];
int find(int x)
{
    return x==father[x] ? x:father[x]=find(father[x]);
}
void init()
{
    for(int i = 1; i <= n; i++)
    {
        father[i] = i;
    }
}
void Union(int x, int y)
{
    flag = 0;
    int f1 = find(x);
    int f2 = find(y);
    if(f1 != f2)
    {
        flag = 1;
        father[f2] = f1;
    }
}
bool cmp(node a, node b)
{
    return a.c < b.c;
}
int main()
{
    int k;
    while(~scanf("%d%d",&n,&k))
    {
        init();
        int m;
        for(int i = 1; i <= k; i++)
        {
            scanf("%d",&m);
            father[m] = -1;
        }
        int l = 0;
        int cost;
        for(int i = 1; i <= n; i++)
        {
            for(int j = 1; j <= n; j++)
            {
                scanf("%d",&cost);
                cc[l].x = i, cc[l].y = j;
                cc[l].c = cost;
                l++;
            }
        }
        int num = n*n;
        sort(cc,cc+num,cmp);
        int ans = 0;
        for(int i = 1; i <= num; i++)
        {
            Union(cc[i].x, cc[i].y);
            if(flag)
                ans+=cc[i].c;
        }
        printf("%d\n",ans);
    }
    return 0;
}


URAL 1982. Electrification Plan(并查集)

标签:UI   size   ant   cost   lan   isis   output   vertica   can   

原文地址:http://www.cnblogs.com/jzdwajue/p/6955806.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!