티스토리 뷰

PS

[백준] 17398번 통신망 분할 C++

Eastplanet 2022. 7. 30. 19:11

문제 출처: https://www.acmicpc.net/problem/17398

 

17398번: 통신망 분할

첫 번째 줄에는 통신탑의 개수인 자연수 N, 통신탑 사이의 연결의 개수인 자연수 M, 통신망 연결 분할 횟수인 자연수 Q가 공백으로 구분되어 주어진다. (1 ≤ N ≤ 100,000, 1 ≤ M ≤ 100,000, 1 ≤ Q 

www.acmicpc.net

해당 문제가 유니온파인드 인 것을 알고 접근했지만 문제에서는 집합을 분리하는 연산을 요구했다.

주어지는 통신탑 간의 연결에서 하나씩 연결을 끊어가며 세는 방법보다는 

주어지는 통신탑 간의 연결에서 모든 연결 끊기 요청을 수행한 상태에서 역순으로 하나씩 병합을 하는 방법을 통해 해결할 수 있었다.

 

#include<iostream>
#include<algorithm>
#include<vector>
#include<queue>
#include<cstring>
#include <string>
#include <math.h>

using namespace std;

typedef pair<int, int>P;

P connect[100001];
int disconnect[100001];
int linearDisconnect[100001];

int u[100001];

int find(int a) {
    if (u[a] < 0)return a;
    return u[a] = find(u[a]);
}

unsigned long long merge(int a, int b) {
    a = find(a);
    b = find(b);
    if (a == b)return 0;
    if (u[a] < u[b]) {
        int temp = u[a];
        int temp2 = u[b];
        u[a] += u[b];
        u[b] = a;
        return (unsigned long long)temp * (unsigned long long)temp2;
    }
    else {
        int temp = u[a];
        int temp2 = u[b];
        u[b] += u[a];
        u[a] = b;
        return (unsigned long long)temp * (unsigned long long)temp2;
    }
}


int main() {
    ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);

    int N, M, Q; cin >> N >> M >> Q;

    fill(&u[0], &u[100001], -1);


    
    for (int i = 0; i < M; i++) {
        int a, b;
        cin >> a >> b;
        connect[i + 1] = P{ a,b };
    }

    for (int i = 0; i < Q; i++) {
        int temp; cin >> temp;
        linearDisconnect[i] = temp;
        disconnect[temp] = 1;
    }

    for (int i = 1; i <= M; i++) {
        if (disconnect[i] == 1)continue;
        
        merge(connect[i].first, connect[i].second);
    }

    unsigned long long sum = 0;

    for (int i = Q - 1; i >= 0; i--) {
        int idx = linearDisconnect[i];
        unsigned long long val = merge(connect[idx].first, connect[idx].second);
        sum += val;
    }

    cout << sum;
    
}
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2026/01   »
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
글 보관함