그럴듯한 개발 블로그
반응형

https://school.programmers.co.kr/learn/courses/30/lessons/86971?language=cpp 

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

연결된 전력망을 하나씩 끊었을 때 모든 상황을 다 찾아서 비교한다.

#include <vector>
#include <algorithm>
#include <cstdlib>
#include <unordered_set>
using namespace std;

int N;

int getDiffWithCutWire(vector<vector<int> > wires, int cutIdx) { // ref로 받지 않았다 복사한 wires임
    unordered_set<int> groupA;
    groupA.insert(wires[cutIdx][0]);
    unordered_set<int> groupB;
    groupB.insert(wires[cutIdx][1]);
    
    wires.erase(wires.begin() + cutIdx);
    
    while (groupA.size() + groupB.size() < N) {
        for (int i = 0; i < wires.size(); i++){
            int tower1 = wires[i][0];
            int tower2 = wires[i][1];
            if (groupA.find(tower1) != groupA.end())
                groupA.insert(tower2);
            else if (groupA.find(tower2) != groupA.end())
                groupA.insert(tower1);
            else if (groupB.find(tower1) != groupB.end())
                groupB.insert(tower2);
            else if (groupB.find(tower2) != groupB.end())
                groupB.insert(tower1);
        }
    }
    return abs((int)groupA.size() - (int)groupB.size());
}

int solution(int n, vector<vector<int>> wires) {
    N = n;
    int res = 2147483647;
    
    for (int i = 0; i < wires.size(); i++)
        res = min(res, getDiffWithCutWire(wires, i));
    
    return res;
}

이거 좀 잘푼거같다 ㅎ

반응형
profile

그럴듯한 개발 블로그

@donghyk2

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!