Post

[C++]๋ฐฑ์ค€ 17197๋ฒˆ Fence Planning

[C++]๋ฐฑ์ค€ 17197๋ฒˆ Fence Planning

๐Ÿ“Œ๋ฌธ์ œ ๋งํฌ


https://www.acmicpc.net/problem/17197

แ„‰แ…ณแ„แ…ณแ„…แ…ตแ†ซแ„‰แ…ฃแ†บ 2025-01-04 แ„‹แ…ฉแ„’แ…ฎ 10 47 24

๐Ÿ“Œ๋ฌธ์ œ ์„ค๋ช…


๊ฐ ์ง‘ํ•ฉ์˜ ((x์ตœ๋Œ“๊ฐ’ - x์ตœ์†Ÿ๊ฐ’) + (y์ตœ๋Œ“๊ฐ’ - y์ตœ์†Ÿ๊ฐ’)) * 2์ค‘ ๊ฐ€์žฅ ์ž‘์€ ๊ฐ’์„ ์ถœ๋ ฅํ•˜๋ฉด ๋ฉ๋‹ˆ๋‹ค. ๋ถ„๋ฆฌ์ง‘ํ•ฉ์œผ๋กœ๋„ ๊ฐ€๋Šฅํ•˜๊ณ  dfs๋กœ๋„ ํ’€์ด ๊ฐ€๋Šฅํ•ฉ๋‹ˆ๋‹ค.

๐Ÿ“Œ์ฝ”๋“œ


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include <iostream>
#include <algorithm>
#include <vector>
#include <climits>
using namespace std;
vector<pair<int,int>> cord, link;
int N, M, parent[100001];

void input(){
    cin >> N >> M;
    cord.resize(N);
    for(auto &it : cord){
        cin >> it.first >> it.second;
    }
    link.resize(M);
    for(auto &it : link){
        cin >> it.first >> it.second;
    }
}

void init(){
    for(int i = 0; i <= N; i++){
        parent[i] = i;
    }
}

int findParent(int x){
    if(parent[x] == x){
        return x;
    }
    return parent[x] = findParent(parent[x]);
}

void unite(int a, int b){
    a = findParent(a);
    b = findParent(b);
    if (a != b) {
        if (a < b) {
            parent[b] = a;
        } else {
            parent[a] = b;
        }
    }
}

void solve(){
    input();
    init();
    for(auto it : link){
        unite(it.first - 1, it.second - 1);
    }
    vector<int> x_min(N, INT_MAX), x_max(N, INT_MIN);
    vector<int> y_min(N, INT_MAX), y_max(N, INT_MIN);
    for(int i = 0; i < N; i++){
        int root = findParent(i);
        x_min[root] = min(x_min[root], cord[i].first);
        x_max[root] = max(x_max[root], cord[i].first);
        y_min[root] = min(y_min[root], cord[i].second);
        y_max[root] = max(y_max[root], cord[i].second);
    }
    int ans = INT_MAX;
    for(int i = 0; i < N; i++){
        if(x_min[i] == INT_MAX){
            continue;
        }
        ans = min(ans, 2 * (x_max[i] - x_min[i] + y_max[i] - y_min[i]));
    }
    cout << ans;
}

int main(){
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    solve();
    return 0;
}
This post is licensed under CC BY 4.0 by the author.