您的位置:首页 > 其它

ural 1982. Electrification Plan 并查集

2015-08-20 17:53 253 查看
题目链接:http://acm.timus.ru/problem.aspx?space=1&num=1982

题意描述:给定N个点,其中K个点是有电的,再给定N*N个彼此之间的距离,求让所有点通电的最小花费;

思路大致是用一个虚点连接这K个有电的点,抽象成一个最小生成树模型,或用并查集的方法从最短边开始迭代;

直接上AC代码:

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <stdio.h>
#include <string>
#include <algorithm>
#include <vector>
#include <queue>
#include <cmath>
#include <map>
using namespace std;

struct Node{
int a, b;
int cost;
};

bool cmp(Node a, Node b){
return a.cost < b.cost;
}

vector<int>parent;
vector<Node>rout;

int getParent(int n){
if (n == parent
)return n;
else if (parent
== -1)return -1;
else return parent
= getParent(parent
);
}

bool link(int x, int y){
int a = getParent(x);
int b = getParent(y);
if (a != b){
if (a < b)
parent[b] = a;
else
parent[a] = b;
return true;
}
return false;
}

void func(){

int n, k;

cin >> n >> k;
for (int i = 0; i < n; i++)
parent.push_back(i);

int num;
for (int i = 0; i < k; i++){
cin >> num;
parent[num - 1] = -1;
}

int len = n*n;
Node node;

for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++){
int cost;
cin >> cost;
node.a = i;
node.b = j;
node.cost = cost;
rout.push_back(node);
}
}

sort(rout.begin(), rout.end(), cmp);

int ans = 0, cost = 0;

for (int i = 0; i < len; i++){
if (link(rout[i].a, rout[i].b))
ans += rout[i].cost;
}

cout << ans << endl;

}

int main(){

freopen("out.txt", "w", stdout);
freopen("in.txt", "r", stdin);

func();

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: