알고리듬/문제

[baekjoon] 10021

narmeee 2023. 5. 20. 03:52

Watering the Fields 

문제

Due to a lack of rain, Farmer John wants to build an irrigation system to send water between his N fields (1 <= N <= 2000).

Each field i is described by a distinct point (xi, yi) in the 2D plane, with 0 <= xi, yi <= 1000. The cost of building a water pipe between two fields i and j is equal to the squared Euclidean distance between them:

(xi - xj)^2 + (yi - yj)^2

FJ would like to build a minimum-cost system of pipes so that all of his fields are linked together -- so that water in any field can follow a sequence of pipes to reach any other field.

Unfortunately, the contractor who is helping FJ install his irrigation system refuses to install any pipe unless its cost (squared Euclidean length) is at least C (1 <= C <= 1,000,000).

Please help FJ compute the minimum amount he will need pay to connect all his fields with a network of pipes.

입력

  • Line 1: The integers N and C.
  • Lines 2..1+N: Line i+1 contains the integers xi and yi.

출력

  • Line 1: The minimum cost of a network of pipes connecting the fields, or -1 if no such network can be built.

예제 입력

3 11
0 2
5 0
4 3

예제 출력

46

풀이

최소 신장 트리를 구하는 문제이다.

일반적인 최소 신장 트리와 다른 점은 가중치에 대한 제한이 있다.

간선을 추가하기전에 가중치가 주어진 값보다 큰 지를 검사해면 된다.

 

#include <iostream>
#include <vector>
#include <queue>

using namespace std;

int n, minimumCost;

typedef struct node{
    int x;
    int y;
    int p;
    node(int ix, int iy, int ip) : x(ix), y(iy), p(ip){}
}node;

vector<node> nodes;

void input(){
    cin >> n >> minimumCost;

    int x, y;
    nodes.push_back(node(-1, -1, -1)); // dummy
    for(int i = 1; i <= n; i++){
        cin >> x >> y;
        nodes.push_back(node(x, y, i));
    }
}

int find_parent(int n1){
    if(nodes[n1].p == n1)return n1;
    else return nodes[n1].p = find_parent(nodes[n1].p);
}

bool make_union(int n1, int n2){
    int p1 = find_parent(n1);
    int p2 = find_parent(n2);
    if(p1 == p2)return false;
    else{
        if(p1 < p2)nodes[p2].p = p1;
        else nodes[p1].p = p2;
        return true;
    }

}

void solve(){
    //cost , from , to
    priority_queue<pair<int, pair<int, int>>, vector<pair<int, pair<int, int>>>, greater<pair<int, pair<int, int>>>> pq;

    for(int i = 1; i < n; i++){
        for(int j = i + 1; j <= n; j++){
            int diffx = nodes[i].x - nodes[j].x;
            int diffy = nodes[i].y - nodes[j].y;
            int dis = diffx * diffx + diffy * diffy;
            if(dis < minimumCost)continue;
            pq.push({dis, {i, j}});
        }
    }
    int cnt = 0, answer = 0;
    while(!pq.empty()){
        int n1 = pq.top().second.first;
        int n2 = pq.top().second.second;
        int dis = pq.top().first;

        pq.pop();

        if(!make_union(n1, n2))continue;
        answer += dis;
        cnt++;
        if(cnt == n - 1)break;
    }
    if(cnt != n - 1)answer = -1;
    cout << answer;
}

int main(){
    input();
    solve();
}