ABOUT ME

์•Œ๊ณ ๋ฆฌ์ฆ˜, ์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์šฉ ๋ธ”๋กœ๊ทธ์ž…๋‹ˆ๋‹น~ ๊ธฐ์ˆ  ๋ธ”๋กœ๊ทธ๋Š” https://velog.io/@ows3090 ์— ์ž‘์„ฑํ•˜๋ ค๊ณ  ํ•ฉ๋‹ˆ๋‹ค.

Today
Yesterday
Total
  • [Programmers] Lv3. ์„ฌ ์—ฐ๊ฒฐํ•˜๊ธฐ
    SW Test/Programmers 2020. 9. 6. 01:42
    ๋ฐ˜์‘ํ˜•
    • ์ด ๊ธ€์€ c++๋กœ ํ’€์ด๋ฅผ ์ž‘์„ฑํ•˜์˜€์Šต๋‹ˆ๋‹ค.

    ๋ฌธ์ œ

    ์˜ˆ์‹œ


    ํ’€์ด

    #include <string>
    #include <vector>
    #include <iostream>
    #include <algorithm>
    using namespace std;
    // ํฌ๋ฃจ์Šค์นผ ์•Œ๊ณ ๋ฆฌ์ฆ˜์œผ๋กœ ํ•ด๊ฒฐ
    // ์—ฃ์ง€ ํ‘œํ˜„ํ•˜๊ธฐ ์œ„ํ•œ ํด๋ž˜์Šค
    class Edge{
    public:
    int s,e,c;
    Edge(int s,int e,int c):s(s),e(e),c(c){};
    };
    // ์—ฃ์ง€ ์ตœ์†Œ ๋น„์šฉ์ˆœ์œผ๋กœ ์ •๋ ฌ
    bool cmp(Edge a, Edge b){
    return a.c < b.c;
    }
    // union-find์—์„œ ๋ถ€๋ชจ๋…ธ๋“œ ์ฐพ๊ธฐ
    int getParent(int parent[], int x){
    if(x == parent[x]){return x;}
    return parent[x] = getParent(parent,parent[x]);
    }
    // union-find ๋ถ€๋ชจ๋…ธ๋“œ ํ•ฉ์น˜๊ธฐ
    void unionParent(int parent[], int a, int b){
    a = getParent(parent, a);
    b = getParent(parent, b);
    if(a<b){
    parent[b] = a;
    }
    else{
    parent[a] = b;
    }
    }
    // union-find ๋ถ€๋ชจ๋…ธ๋“œ ๊ฐ™์€์ง€ ์ฐพ๊ธฐ
    int findParent(int parent[], int a, int b){
    a = getParent(parent, a);
    b = getParent(parent, b);
    if(a == b)return 1;
    else return 0;
    }
    int solution(int n, vector<vector<int>> costs) {
    int answer = 0;
    int check[100];
    for(int i=0;i<100;i++){
    check[i] = i;
    }
    // ๊ฐ ์ •์ ์„ vec์— ๋„ฃ๊ณ  ๋น„์šฉ์ด ์ ์€ ๊ฐ„์„ ๋ถ€ํ„ฐ ์ •๋ ฌํ•œ๋‹ค.
    vector<Edge> vec;
    for(int i=0;i<costs.size();i++){
    Edge e = Edge(costs[i][0],costs[i][1],costs[i][2]);
    vec.push_back(e);
    }
    sort(vec.begin(),vec.end(),cmp);
    // ๊ฐ ๋…ธ๋“œ๋“ค ๊ด€๊ณ„๊ฐ€ ์‚ฌ์ดํด์ด ์—†์œผ๋ฉด ์ถ”๊ฐ€ํ•œ๋‹ค.
    for(int i=0;i<vec.size();i++){
    if(!findParent(check, vec[i].s, vec[i].e)){
    unionParent(check, vec[i].s, vec[i].e);
    answer+=vec[i].c;
    }
    }
    return answer;
    }
    • ์ถ”๊ฐ€๋กœ ๊ถ๊ธˆํ•œ ์ ์ด๋‚˜ ์ˆ˜์ •ํ•  ๋ถ€๋ถ„ ์žˆ์œผ๋ฉด ๋Œ“๊ธ€๋กœ ๋‚จ๊ฒจ์ฃผ์„ธ์š”.
    ๋ฐ˜์‘ํ˜•
Designed by Tistory.