๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm ๐Ÿง‘๐Ÿป‍๐Ÿ’ป/๋ฐฑ์ค€(BOJ)

[๋ฐฑ์ค€,c++] 14588๋ฒˆ - Line Friends (Small)

by dkswnkk 2021. 11. 11.

๋ฌธ์ œ

 

14588๋ฒˆ: Line Friends (Small)

Q๊ฐœ์˜ ์ค„์— ๊ฑธ์ณ ๋‘ ์„ ๋ถ„์ด ๊ฐ€๊นŒ์šด ์ •๋„๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค. ๋งŒ์•ฝ, ๋‘ ์„ ๋ถ„ ์‚ฌ์ด์˜ ์นœ๊ตฌ ๊ด€๊ณ„๊ฐ€ ๋‹จ์ ˆ๋˜์—ˆ๋‹ค๋ฉด -1์„ ์ถœ๋ ฅํ•œ๋‹ค.

www.acmicpc.net

 

์ฝ”๋“œ

#include <iostream>
#include <vector>
#include <algorithm>
#define INF 1e9
using namespace std;

int N,Q;
int graph[301][301];
vector<pair<int, int>>v;
int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(0);


    cin >> N;
    for (int i = 0; i < 301; i++) {    //์ตœ๋‹จ ๊ฑฐ๋ฆฌ ํ…Œ์ด๋ธ”์„ ๋ชจ๋‘ ๋ฌดํ•œ์œผ๋กœ ์ดˆ๊ธฐํ™”
        fill(graph[i], graph[i] + 301, INF);
    }
    for (int a = 1; a <= N; a++) {    //์ž๊ธฐ ์ž์‹ ์—์„œ ์ž๊ธฐ ์ž์‹ ์œผ๋กœ ๊ฐ€๋Š” ๋น„์šฉ์€ 0์œผ๋กœ ์ดˆ๊ธฐํ™”
        for (int b = 1; b <= N; b++) {
            if (a == b) graph[a][b] = 0;
        }
    }    
    for (int i = 0; i < N; i++) {    //๊ฐ„์„ ์ •๋ณด ์ž…๋ ฅ
        int a, b; cin >> a >> b;
        v.push_back({ a,b });
    }
    for (int i = 1; i <= N; i++) {
        for (int k = 1; k <= N; k++) {
            if (v[i-1].second >= v[k-1].first && v[k-1].second >= v[i-1].first) {    //๊ทธ๋ž˜ํ”„๊ฐ€ ๊ฒน์น˜๋Š” ๋ถ€๋ถ„์ด ์žˆ์„๋•Œ ์นœ๊ตฌ๊ด€๊ณ„์ด๋‹ค.
                graph[i][k] = 1;
                graph[k][i] = 1;
            }
        }
    }
    for (int k = 1; k <= N; k++) {    //ํ”Œ๋กœ์ด๋“œ-์™€์ƒฌ ์•Œ๊ณ ๋ฆฌ์ฆ˜ ์ˆ˜ํ–‰
        for (int a = 1; a <= N; a++) {
            for (int b = 1; b <= N; b++) {
                graph[a][b] = min(graph[a][b], graph[a][k] + graph[k][b]);
            }
        }
    }

    cin >> Q;
    for (int i = 0; i < Q; i++) {    //์„ ๋ถ„์ด ๊ฐ€๊นŒ์šด ์ •๋„๋ฅผ ์ถœ๋ ฅ.
        int a, b; cin >> a >> b;
        if (graph[a][b] == INF) cout << -1 << "\n";
        else cout << graph[a][b] << "\n";
    }
}

๋Œ“๊ธ€