๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ”ฅ PS(Problem Solving) ๐Ÿ”ฅ/BOJ

[BOJ] #2644 ์ดŒ์ˆ˜๊ณ„์‚ฐ

by dar0m! 2019. 9. 4.
์‹œ๊ฐ„ ์ œํ•œ ๋ฉ”๋ชจ๋ฆฌ ์ œํ•œ ์ •๋‹ต ๋น„์œจ
1 ์ดˆ 128 MB 44.604 %

 

 

2644๋ฒˆ: ์ดŒ์ˆ˜๊ณ„์‚ฐ

์‚ฌ๋žŒ๋“ค์€ 1, 2, 3, โ€ฆ, n (1โ‰คnโ‰ค100)์˜ ์—ฐ์†๋œ ๋ฒˆํ˜ธ๋กœ ๊ฐ๊ฐ ํ‘œ์‹œ๋œ๋‹ค. ์ž…๋ ฅ ํŒŒ์ผ์˜ ์ฒซ์งธ ์ค„์—๋Š” ์ „์ฒด ์‚ฌ๋žŒ์˜ ์ˆ˜ n์ด ์ฃผ์–ด์ง€๊ณ , ๋‘˜์งธ ์ค„์—๋Š” ์ดŒ์ˆ˜๋ฅผ ๊ณ„์‚ฐํ•ด์•ผ ํ•˜๋Š” ์„œ๋กœ ๋‹ค๋ฅธ ๋‘ ์‚ฌ๋žŒ์˜ ๋ฒˆํ˜ธ๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ๊ทธ๋ฆฌ๊ณ  ์…‹์งธ ์ค„์—๋Š” ๋ถ€๋ชจ ์ž์‹๋“ค ๊ฐ„์˜ ๊ด€๊ณ„์˜ ๊ฐœ์ˆ˜ m์ด ์ฃผ์–ด์ง„๋‹ค. ๋„ท์งธ ์ค„๋ถ€ํ„ฐ๋Š” ๋ถ€๋ชจ ์ž์‹๊ฐ„์˜ ๊ด€๊ณ„๋ฅผ ๋‚˜ํƒ€๋‚ด๋Š” ๋‘ ๋ฒˆํ˜ธ x,y๊ฐ€ ๊ฐ ์ค„์— ๋‚˜์˜จ๋‹ค. ์ด๋•Œ ์•ž์— ๋‚˜์˜ค๋Š” ๋ฒˆํ˜ธ x๋Š” ๋’ค์— ๋‚˜์˜ค๋Š” ์ •์ˆ˜ y์˜ ๋ถ€๋ชจ ๋ฒˆํ˜ธ๋ฅผ ๋‚˜ํƒ€๋‚ธ๋‹ค. ๊ฐ ์‚ฌ๋žŒ์˜ ๋ถ€๋ชจ๋Š” ์ตœ๋Œ€

www.acmicpc.net

์ „์ฒด ์‚ฌ๋žŒ ์ˆ˜ n, ์ดŒ์ˆ˜๋ฅผ ๊ณ„์‚ฐํ•ด์•ผ ํ•˜๋Š” ์„œ๋กœ ๋‹ค๋ฅธ ์‚ฌ๋žŒ์˜ ๋ฒˆํ˜ธ x, y ๊ด€๊ณ„์˜ ์ˆ˜ m ์ด ์ฃผ์–ด์ง€๋ฉด ์•„๋ž˜์˜ m๊ฐœ์˜ ์ค„์— ๋ถ€๋ชจ-์ž์‹ ๊ด€๊ณ„๋ฅผ ๋‚˜ํƒ€๋‚ด๋Š” a,b๊ฐ€ ์ฃผ์–ด์ง„๋‹ค.

m๊ฐœ์˜ ์ค„์— ํ•ด๋‹นํ•˜๋Š” ๊ด€๊ณ„์— ๋”ฐ๋ผ์„œ vector ๋กœ 2์ฐจ์› ๋ฐฐ์—ด์„ ํ˜•์„ฑํ•˜๊ณ  bfs๋ฅผ ํ™œ์šฉํ•˜์—ฌ ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•˜์˜€๋‹ค.

 

๋ฉ”๋ชจ๋ฆฌ ์‹œ๊ฐ„
1988 KB 0 ms
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
32
33
34
35
36
37
38
39
40
41
42
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<string.h>
#include<vector>
#include<queue>
using namespace std;
typedef pair<intint> p;
 
int n, m, x, y;
vector<vector<int>> v;
queue<p> q;
int chk[101];
 
int main() {
    scanf("%d %d %d %d"&n, &x, &y, &m);
    v.resize(n * m);
    for (int i = 0, a, b; i < m; i++) {
        scanf("%d %d"&a, &b);
        v[a].push_back(b);
        v[b].push_back(a);
    }
    q.push({ x,0 });
    while (!q.empty()) {
        int pnum = q.front().first;
        int pcnt = q.front().second;
        q.pop();
        if (pnum == y) {
            printf("%d", pcnt);
            return 0;
        }
 
        for (auto e : v[pnum]) {
            if (!chk[e]) {
                chk[e] = 1;
                q.push({ e, pcnt + 1 });
            }
        }
    }
    printf("-1");
    return 0;
}
cs

 

๋Œ“๊ธ€