๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm ๐Ÿง‘๐Ÿป‍๐Ÿ’ป/ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค(Programmers)

[c++] ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ๋ฐฐ๋‹ฌ( Level2)

by dkswnkk 2021. 11. 8.

๋ฌธ์ œ

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ๋ฐฐ๋‹ฌ

5 [[1,2,1],[2,3,3],[5,2,2],[1,4,2],[5,3,1],[5,4,2]] 3 4 6 [[1,2,1],[1,3,2],[2,3,2],[3,4,3],[3,5,2],[3,5,3],[5,6,1]] 4 4

programmers.co.kr

 

์ฝ”๋“œ

#include <iostream>
#include <vector>
#define INF 1e9

using namespace std;



int solution(int N, vector<vector<int> > road, int K) {
    int graph[51][51]={0, };
    int answer = 0;
    vector<int>memory_city_cnt;

    for(int i=0; i<N; i++){
        for(int k=0; k<N; k++){
            if(i==k) graph[i][k] = 0;
            else graph[i][k] = INF;
        }
    }

    for(int i=0; i<road.size(); i++){
        int a = road[i][0]-1;
        int b = road[i][1]-1;
        int cost = road [i][2];
        graph[a][b] = min(graph[a][b],cost);
        graph[b][a] = min(graph[b][a],cost);
    }

    for(int k=0; k<N; k++){
        for(int a=0; a<N; a++){
            for(int b=0; b<N; b++){
                graph[a][b]=min(graph[a][b],graph[a][k]+graph[k][b]);
            }
        }
    }

    for(int k=0; k<N; k++){
        if(graph[0][k]<=K) memory_city_cnt.push_back(k);
    }

    answer = memory_city_cnt.size();
    return answer;
}

 

ํ’€์ด

์ผ๋ฐ˜์ ์ธ ํ”Œ๋กœ์ด๋“œ-์™€์ƒฌ ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ์ˆ˜ํ–‰ํ•œ ํ›„ ๋งˆ์ง€๋ง‰์— ๋ฌธ์ œ์˜ ์กฐ๊ฑด์— ๋งž๊ฒŒ 1๋ฒˆ ๋งˆ์„์— ์žˆ๋Š” ์Œ์‹์ ์ด K ์ดํ•˜์˜ ์‹œ๊ฐ„์— ๋ฐฐ๋‹ฌ์ด ๊ฐ€๋Šฅํ•œ ๋งˆ์„์˜ ๊ฐœ์ˆ˜๋ฅผ ์ถœ๋ ฅํ•˜๋ฉด ๋˜๋Š” ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.

์ฃผ์˜ํ•ด์•ผ ํ•  ์ ์€ ์ž…๋ ฅ์—์„œ ์•„๋ž˜์˜ ์‚ฌ์ง„๊ณผ ๊ฐ™์ด ํ•œ ๋„๋กœ์˜ ์ •๋ณด๊ฐ€ ์ค‘๋ณตํ•ด์„œ ์ฃผ์–ด์ง€๊ธฐ ๋•Œ๋ฌธ์— ์ž…๋ ฅ์„ ๋ฐ›์„ ๋•Œ ์ตœ์†Œ ๊ฐ’์œผ๋กœ ๊ฐฑ์‹ ํ•ด์ค˜์•ผ ํ•ฉ๋‹ˆ๋‹ค.

 

๋Œ“๊ธ€