반응형

https://www.acmicpc.net/problem/14699

 

14699번: 관악산 등산

서울대학교에는 “누가 조국의 미래를 묻거든 고개를 들어 관악을 보게 하라”라는 유명한 문구가 있다. 어느 날 Unused는 Corea에게 조국의 미래를 물었고, Corea는 직접 관악산에 올라가 조국의 미

www.acmicpc.net

 

 

[ 문제풀이 ]

 

1. dp[ 5001 ]을 선언하고 -1로 초기화해 줍니다.

 

2. 1번 노드부터 N번 노드까지 dfs를 돌면서 갈 수 있는 쉼터의 최댓값을 다음의 점화식을 이용하여 dp[ i ]에 저장합니다.

dp[ i ] = max( dp[ i ], dfs(next) + 1 )

 

3. 1번 노드부터 N번 노드까지 dfs( i )를 출력합니다.

 

[ 소스코드 ]

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
43
44
45
46
47
48
49
50
#include<iostream>
#include<vector>
 
using namespace std;
 
int N, M;
int H[5001];
int dp[5001];
vector<int> list[5001];
 
int dfs(int cur)
{
    if (dp[cur] != -1return dp[cur];
    int& ret = dp[cur];
    ret = 1;
 
    for (auto& next : list[cur]) {
        if (H[cur] < H[next]) {
            ret = max(ret, dfs(next) + 1);
        }
    }
 
    return ret;
}
 
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
 
    cin >> N >> M;
 
    for (int i = 1; i <= N; i++) {
        cin >> H[i];
        dp[i] = -1;
    }
 
    for (int i = 0; i < M; i++) {
        int u, v;
        cin >> u >> v;
        
        list[u].push_back(v);
        list[v].push_back(u);
    }
 
    for (int i = 1; i <= N; i++) {
        cout << dfs(i) << '\n';
    }
}
cs
반응형
반응형

https://www.acmicpc.net/problem/25498

 

25498번: 핸들 뭘로 하지

효규가 얻을 수 있는 문자열은 사전순으로 "$\text{aa}$", "$\text{aaa}$", "$\text{aaaa}$", "$\text{aaaa}$"이므로 "$\text{aaaa}$"를 핸들로 정한다.

www.acmicpc.net

 

 

[ 문제풀이 ]

 

1. 문자열과 그래프를 입력받고, arr[500001]과 vector<int> list[500001]에 저장합니다.

 

2. node struct를 만들어 현재 노드의 번호, 인덱스 그리고 부모의 문자를 저장합니다.

 

3. queue<node> q를 만들어 bfs를 돌면서 해당 인덱스에서 가장 큰 문자를 ans에 더해주면서 문자열을 완성합니다.

 

4. ans를 출력합니다.

 

[ 소스코드 ]

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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include<iostream>
#include<vector>
#include<queue>
#include<string>
 
using namespace std;
 
struct node {
    int cur, idx;
    char parent;
};
 
int N;
char arr[500001];
vector<int> list[500001];
int visited[500001];
string ans;
 
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
 
    cin >> N >> arr;
 
    for (int i = 0; i < N - 1; i++) {
        int u, v;
        cin >> u >> v;
        list[u].push_back(v);
        list[v].push_back(u);
    }
 
    queue<node> q;
    q.push({ 11'0'});
    visited[1= 1;
    ans += '0';
 
    while (!q.empty()) {
        const int cur = q.front().cur;
        const int idx = q.front().idx;
        const char pa = q.front().parent;
        q.pop();
 
        if (pa != ans[idx - 1]) continue;
        if (idx >= ans.size()) ans += arr[cur - 1];
        else if (ans[idx] < arr[cur - 1]) {
            ans[idx] = arr[cur - 1];
        }
 
        for (auto& next : list[cur]) {
            if (visited[next] != 1) {
                visited[next] = 1;
                q.push({ next,idx + 1, arr[cur - 1]});
            }
        }
    }
 
    ans.erase(ans.begin());
 
    cout << ans;
}
cs
반응형
반응형

https://www.acmicpc.net/problem/21276

 

21276번: 계보 복원가 호석

석호촌에는 N 명의 사람이 살고 있다. 굉장히 활발한 성격인 석호촌 사람들은 옆 집 상도 아버님, 뒷집 하은 할머님 , 강 건너 유리 어머님 등 모두가 한 가족처럼 살아가고 있다. 그러던 어느 날

www.acmicpc.net

 

 

[ 문제풀이 ]

이 문제를 풀기 전에 다음 글을 먼저 읽고 오시는 것을 추천드립니다.

https://rudalsd.tistory.com/72

 

[ 알고리즘 ] 위상 정렬 알고리즘(Topological Sort Algorithm)

1. 위상 정렬 알고리즘(Topological Sort Algorithm)이란? 위상 정렬 알고리즘(Topological Sort Algorithm)은 어떤 일을 하는 순서를 찾는 알고리즘입니다. 만약 먼저 방문해야 하는 노드가 있다면 그 노드를 방

rudalsd.tistory.com

 

1. 조상으로부터 자손으로 이어지는 단방향 그래프를 list 배열에 저장합니다.

 

2. 1과 동시에 조상의 개수를 cnt[ i ]++를 통해 저장해 주고, cnt[ i ]가 0이면 queue에 넣어줍니다.

 

3. queue를 돌면서 cnt[ i ]가 0일 때 queue에 해당 자손을 넣어주고, 그때의 조상이 직계 조상이므로 child 배열에 해당 자손을 넣어줍니다.

 

4. 가장 초기에 cnt[ i ]가 0인 조상은 가문의 시조이므로 parent 배열에 넣어줍니다.

 

5. 조건에 맞게 출력해 줍니다.

 

[ 소스코드 ]

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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include<iostream>
#include<algorithm>
#include<string>
#include<vector>
#include<queue>
#include<map>
 
using namespace std;
 
int N, M;
map<stringint> m;
string str[1000];
int cnt[1000];
map<stringvector<string>> child;
vector<int> list[1000];
vector<string> parent;
 
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
 
    cin >> N;
 
    for (int i = 0; i < N; i++) {
        cin >> str[i];
        m[str[i]] = i;
    }
 
    cin >> M;
 
    for (int i = 0; i < M; i++) {
        string tmp[2];
        cin >> tmp[0>> tmp[1];
        cnt[m[tmp[0]]]++;
        list[m[tmp[1]]].push_back(m[tmp[0]]);
    }
 
    queue<int> q;
 
    for (int i = 0; i < N; i++) {
        if (cnt[i] == 0) {
            q.push(i);
            parent.push_back(str[i]);
        }
    }
 
    while (!q.empty()) {
        const int cur = q.front();
        q.pop();
 
        for (auto& next : list[cur]) {
            cnt[next]--;
            if (cnt[next] == 0) {
                child[str[cur]].push_back(str[next]);
                q.push(next);
            }
        }
    }
 
    sort(parent.begin(), parent.end());
 
    cout << parent.size() << '\n';
 
    for (auto& next : parent) {
        cout << next << ' ';
    }
 
    cout << '\n';
 
    sort(str, str + N);
 
    for (int i = 0; i < N; i++) {
        cout << str[i] << ' ' << child[str[i]].size() << ' ';
        sort(child[str[i]].begin(), child[str[i]].end());
        for (auto& next : child[str[i]]) {
            cout << next << ' ';
        }
        cout << '\n';
    }
}
cs
반응형
반응형

https://www.acmicpc.net/problem/2186

 

2186번: 문자판

첫째 줄에 N(1 ≤ N ≤ 100), M(1 ≤ M ≤ 100), K(1 ≤ K ≤ 5)가 주어진다. 다음 N개의 줄에는 M개의 알파벳 대문자가 주어지는데, 이는 N×M 크기의 문자판을 나타낸다. 다음 줄에는 1자 이상 80자 이하의

www.acmicpc.net

 

 

[ 문제풀이 ]

 

1. dp[N][M][str.size]를 선언하고 -1로 초기화해 줍니다.

 

2. 해당 좌표의 값과 str[cnt]의 값이 같다면 재귀함수를 통해 dp[ y ][ x ][ cnt ]의 값을 갱신해 줍니다.

 

3. 모든 좌표에 대해 dp[ y ][ x ][ 0 ]의 값을 ans에 더해주고, ans를 출력합니다.

 

[ 소스코드 ]

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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include<iostream>
#include<string>
 
using namespace std;
 
int N, M, K;
string str;
char arr[100][101];
int dp[100][100][80];
int dy[] = { -1,1,0,0 };
int dx[] = { 0,0,-1,1 };
int ans;
 
int dfs(int y, int x, int cnt)
{
    if (cnt == str.size() - 1) {
        return dp[y][x][cnt] = 1;
    }
    if (dp[y][x][cnt] != -1return dp[y][x][cnt];
    int& ret = dp[y][x][cnt];
    ret = 0;
 
    for (int i = 0; i < 4; i++) {
        for (int j = 1; j <= K; j++) {
            const int yy = y + dy[i] * j;
            const int xx = x + dx[i] * j;
 
            if (yy >= 0 && yy < N && xx >= 0 && xx < M) {
                if (arr[yy][xx] == str[cnt + 1]) {
                    ret += dfs(yy, xx, cnt + 1);
                }
            }
        }
    }
 
    return ret;
}
 
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
 
    cin >> N >> M >> K;
 
    for (int i = 0; i < N; i++) {
        cin >> arr[i];
        for (int j = 0; j < M; j++) {
            for (int k = 0; k < 80; k++) {
                dp[i][j][k] = -1;
            }
        }
    }
    cin >> str;
 
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < M; j++) {
            if (dp[i][j][0== -1 && arr[i][j] == str[0]) {
                ans += dfs(i, j, 0);
            }
        }
    }
 
    cout << ans;
}
cs

 

반응형
반응형

https://www.acmicpc.net/problem/9177

 

9177번: 단어 섞기

입력의 첫 번째 줄에는 1부터 1000까지의 양의 정수 하나가 주어지며 데이터 집합의 개수를 뜻한다. 각 데이터집합의 처리과정은 동일하다고 하자. 각 데이터집합에 대해, 세 개의 단어로 이루어

www.acmicpc.net

 

 

[ 문제풀이 ]

 

1. dp[ 201 ][ 201 ]을 선언하고 -1로 초기화합니다.

 

2. a, b, c 문자열을 입력받고, a[ i + 1 ] == c[ i + j + 1 ] 일 때 dfs(i + 1, j), b[ j + 1 ] == c[ i + j + 1 ] 일 때 dfs(i, j + 1)를 통해 만들 수 있는 문자열인지 체크합니다.

 

3. dfs(0, 0)이 1이라면 yes를 아니라면 no를 출력합니다.

 

[ 소스코드 ]

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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include<iostream>
#include<string>
 
using namespace std;
 
int N;
int dp[201][201];
string a, b, c;
 
int dfs(int i, int j)
{
    if (i + j == c.size() - 1return 1;
     if (dp[i][j] != -1return dp[i][j];
    int& ret = dp[i][j];
    ret = 0;
 
    if (a[i + 1== c[i + j + 1]) {
        ret = max(ret, dfs(i + 1, j));
    }
    
    if (b[j + 1== c[i + j + 1]) {
        ret = max(ret, dfs(i, j + 1));
    }
 
    return ret;
}
 
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
 
    cin >> N;
 
    for(int t = 1;t<=N;t++){
        cin >> a >> b >> c;
 
        a = ' ' + a;
        b = ' ' + b;
        c = ' ' + c;
 
        for (int i = 0; i < a.size(); i++) {
            for (int j = 0; j < b.size(); j++) {
                dp[i][j] = -1;
            }
        }
 
        cout << "Data set " << t << ": ";
 
        if (dfs(00)) {
            cout << "yes";
        }
        else {
            cout << "no";
        }
 
        cout<<'\n';
    }
}
cs
반응형
반응형

https://www.acmicpc.net/problem/20924

 

20924번: 트리의 기둥과 가지

첫 번째 줄에는 노드의 개수 $N$($1 \le N \le 200\,000$)과 루트 노드의 번호 $R$($1 \le R \le N$)이 주어진다. 이후 $N-1$개의 줄에 세 개의 정수 $a$, $b$, $d$($1 \le a, b \le N$, $ a \ne b$)가 주어진다. 이는 $a$번

www.acmicpc.net

 

 

[ 문제풀이 ]

 

1. 그래프를 입력받고, list 배열에 저장합니다.

 

2. dfs를 이용하여 루트부터 탐색하면서 현재 노드까지의 길이를 저장하고, 그중 가장 긴 길이를 all에 저장합니다.

 

3. 자식 노드가 2개 이상인 노드의 길이 중 가장 짧은 길이를 gidung에 저장합니다.

 

4. gidung 과 all - gidung을 출력합니다.

 

[ 소스코드 ]

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
43
44
45
46
47
48
49
50
51
52
53
54
55
#include<iostream>
#include<vector>
 
using namespace std;
 
int N, R;
int a, b, d;
vector<pair<intint>> list[200001];
int visited[200001];
int all;
int gidung = 987654321;
 
void dfs(int node, int dist)
{
    int cnt = 0;
    all = max(all, dist);
    for (auto& next : list[node]) {
        if (visited[next.first] == 0) {
            cnt++;
            visited[next.first] = 1;
            dfs(next.first, dist + next.second);
            visited[next.first] = 0;
        }
    }
 
    if (cnt >= 2) {
        gidung = min(gidung, dist);
    }
}
 
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
 
    cin >> N >> R;
 
    for (int i = 0; i < N - 1; i++) {
        int a, b, d;
        cin >> a >> b >> d;
 
        list[a].push_back({ b,d });
        list[b].push_back({ a,d });
    }
 
    visited[R] = 1;
    dfs(R, 0);
 
    if (gidung == 987654321) {
        gidung = all;
    }
 
    cout << gidung << ' ' << all - gidung;
}
cs
반응형
반응형

https://www.acmicpc.net/problem/3197

 

3197번: 백조의 호수

입력의 첫째 줄에는 R과 C가 주어진다. 단, 1 ≤ R, C ≤ 1500. 다음 R개의 줄에는 각각 길이 C의 문자열이 하나씩 주어진다. '.'은 물 공간, 'X'는 빙판 공간, 'L'은 백조가 있는 공간으로 나타낸다.

www.acmicpc.net

 

 

[ 문제풀이 ]

 

1. 현재 호수의 상태를 저장할 queue<pair<int, int>> water, 다음 호수의 상태를 저장할 queue<pair<int, int>> tmpW, 현재 백조의 위치를 저장할 queue<pair<int, int>> swan, 마지막으로 다음 백조의 위치를 저장할 queue<pair<int, int>> tmpS를 선언합니다.

 

2. 호수를 입력받으면서 얼음이 아닌 좌표를 water에 push 하고, 백조 한 마리의 위치를 swan에 push 합니다.

 

3. 먼저 백조가 만날 수 있는지 bfs를 통해 움직이고, 벽에 마주칠 때마다 다음에 갈 수 있는 위치이므로 tmpS에 push 하고, 백조를 만난다면 Find 변수를 true로 갱신합니다.

 

4. 빙하가 녹으면서 현재 물에 맞닿아 있다면 tmpW에 push 해줍니다.

 

5. Find 변수가 true라면 ans를 출력해 주고, 그렇지 않다면 water = tmpW, swan = tmpS로 갱신해 주고, ans++를 해줍니다.

 

[ 소스코드 ]

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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#include<iostream>
#include<queue>
 
using namespace std;
 
int R, C;
int r, c;
char arr[1500][1501];
int visited[1500][1500];
int dr[] = { -1,1,0,0 };
int dc[] = { 0,0,-1,1 };
queue<pair<intint>> swan, water, tmpW, tmpS;
bool Find = false;
 
void BFSwater()
{
    while (!water.empty()) {
        const int r = water.front().first;
        const int c = water.front().second;
        water.pop();
 
        for (int i = 0; i < 4; i++) {
            const int rr = r + dr[i];
            const int cc = c + dc[i];
 
            if (rr >= 0 && rr < R && cc >= 0 && cc < C) {
                if (arr[rr][cc] == 'X') {
                    tmpW.push({ rr,cc });
                    arr[rr][cc] = '.';
                }
            }
        }
    }
}
 
void BFSswan()
{
    while (!swan.empty() && Find == false) {
        const int r = swan.front().first;
        const int c = swan.front().second;
        swan.pop();
 
        for (int i = 0; i < 4; i++) {
            const int rr = r + dr[i];
            const int cc = c + dc[i];
 
            if (rr >= 0 && rr < R && cc >= 0 && cc < C && visited[rr][cc] == 0) {
                visited[rr][cc] = 1;
                if (arr[rr][cc] == '.') {
                    swan.push({ rr,cc });
                }
                else if (arr[rr][cc] == 'X') {
                    tmpS.push({ rr,cc });
                    arr[rr][cc] = '.';
                }
                else if (arr[rr][cc] == 'L') {
                    Find = true;
                    break;
                }
            }
        }
    }
}
 
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
 
    cin >> R >> C;
 
    
 
    for (int i = 0; i < R; i++) {
        cin >> arr[i];
        for (int j = 0; j < C; j++) {
            if (arr[i][j] != 'X') {
                water.push({ i,j });
            }
            if (arr[i][j] == 'L') {
                r = i;
                c = j;
            }
        }
    }
 
    swan.push({ r,c });
    visited[r][c] = 1;
 
    int ans = 0;
 
    while (1) {
        BFSswan();
        if (Find == true) {
            cout << ans;
            return 0;
        }
        BFSwater();
        ans++;
 
        water = tmpW;
        swan = tmpS;
 
        tmpW = queue<pair<intint>>();
        tmpS = queue<pair<intint>>();
    }
}
cs
반응형
반응형

https://www.acmicpc.net/problem/13565

 

13565번: 침투

첫째 줄에는 격자의 크기를 나타내는  M (2 ≤ M ≤ 1,000) 과 N (2 ≤ N ≤ 1,000) 이 주어진다. M줄에 걸쳐서, N개의 0 또는 1 이 공백 없이 주어진다. 0은 전류가 잘 통하는 흰색, 1은 전류가 통하지 않

www.acmicpc.net

 

 

[ 문제풀이 ]

 

1. 격자를 입력받고, 격자의 y 좌표가 0인 좌표의 arr 값이 '0'이라면 queue에 넣고, visited 배열을 만들어 방문 여부를 저장합니다.

 

2. bfs를 이용하여 arr의 값이 '0'인 좌표로만 이동하면서 y 좌표의 값이 M이상인 경우가 있다면 YES를, 그렇지 않다면 NO를 출력합니다.

 

[ 소스코드 ]

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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include<iostream>
#include<queue>
 
using namespace std;
 
int M, N;
char arr[1000][1001];
int visited[1000][1000];
int dy[] = { -1,1,0,0 };
int dx[] = { 0,0,-1,1 };
 
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
 
    cin >> M >> N;
 
    for (int i = 0; i < M; i++) {
        cin >> arr[i];
    }
 
    queue<pair<intint>> q;
 
    for (int i = 0; i < N; i++) {
        if (arr[0][i] == '0') {
            q.push({ 0,i });
            visited[0][i] = 1;
        }
    }
 
    while (!q.empty()) {
        const int y = q.front().first;
        const int x = q.front().second;
        q.pop();
 
        for (int i = 0; i < 4; i++) {
            const int yy = y + dy[i];
            const int xx = x + dx[i];
 
            if (yy >= 0 && yy < M && xx >= 0 && xx < N) {
                if (visited[yy][xx] == 0 && arr[yy][xx] == '0') {
                    visited[yy][xx] = 1;
                    q.push({ yy,xx });
                }
            }
            else if (yy == M) {
                cout << "YES";
                return 0;
            }
        }
    }
 
    cout << "NO";
}
cs
반응형
반응형

https://www.acmicpc.net/problem/12761

 

12761번: 돌다리

동규와 주미는 일직선 상의 돌 다리 위에있다. 돌의 번호는 0 부터 100,000 까지 존재하고 동규는 \(N\)번 돌 위에, 주미는 \(M\)번 돌 위에 위치하고 있다. 동규는 주미가 너무 보고싶기 때문에 최대

www.acmicpc.net

 

 

[ 문제풀이 ]

 

1. A, B, N, M을 입력받고, visited 배열을 만들어 방문 여부를 저장합니다.

 

2. bfs를 이용하여 8가지 경우의 수를 통해 이동하면서 cnt값을 올려주고, 현재 위치가 M이라면 cnt 값을 출력하고 종료합니다.

[ 소스코드 ]

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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include<iostream>
#include<queue>
 
using namespace std;
 
int A, B, N, M;
int visited[100001];
 
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
 
    cin >> A >> B >> N >> M;
 
    queue<pair<intint>>q;
    q.push({ N,0 });
 
    visited[N] = 1;
 
    while (!q.empty()) {
        const int cur = q.front().first;
        const int cnt = q.front().second;
        q.pop();
 
        if (cur == M) {
            cout << cnt;
            return 0;
        }
 
        if (cur < M) {
            if (cur + 1 <= 100000 && visited[cur + 1== 0) {
                visited[cur + 1= 1;
                q.push({ cur + 1,cnt + 1 });
            }
 
            if (cur + A <= 100000 && visited[cur + A] == 0) {
                visited[cur + A] = 1;
                q.push({ cur + A,cnt + 1 });
            }
 
            if (cur + B <= 100000 && visited[cur + B] == 0) {
                visited[cur + B] = 1;
                q.push({ cur + B,cnt + 1 });
            }
 
            if (cur * A <= 100000 && visited[cur * A] == 0) {
                visited[cur * A] = 1;
                q.push({ cur * A,cnt + 1 });
            }
 
            if (cur * B <= 100000 && visited[cur * B] == 0) {
                visited[cur * B] = 1;
                q.push({ cur * B,cnt + 1 });
            }
        }
 
        if (cur - 1 >= 0 && visited[cur - 1== 0) {
            visited[cur - 1= 1;
            q.push({ cur - 1,cnt + 1 });
        }
 
        if (cur - A >= 0 && visited[cur - A] == 0) {
            visited[cur - A] = 1;
            q.push({ cur - A,cnt + 1 });
        }
 
        if (cur - B >= 0 && visited[cur - B] == 0) {
            visited[cur - B] = 1;
            q.push({ cur - B,cnt + 1 });
        }
    }
}
cs
반응형
반응형

https://www.acmicpc.net/problem/20183

 

20183번: 골목 대장 호석 - 효율성 2

첫 줄에 교차로 개수 N, 골목 개수 M, 시작 교차로 번호 A, 도착 교차로 번호 B, 가진 돈 C 가 공백으로 구분되어 주어진다. 이어서 M 개의 줄에 걸쳐서 각 골목이 잇는 교차로 2개의 번호와, 골목의

www.acmicpc.net

 

 

[ 문제풀이 ]

 

1. 그래프를 입력받고, vector<pair<int, int>> list[ 100001 ] 배열에 저장합니다. 

 

2. 매개 변수를 활용하여 이동할 수 있는 골목의 최대 비용을 정해서 dijkstra를 돌립니다.

 

3. ans를 -1로 초기화하고, 만약 도착지에 도착하게 되면 ans에 해당 매개 변수 값을 저장합니다.

 

4. ans를 출력합니다.

 

[ 소스코드 ]

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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include<iostream>
#include<queue>
#include<vector>
#define ll long long
 
using namespace std;
 
int N, M;
int A, B;
ll C;
vector<pair<intint>> list[100001];
int s, e;
int ans = -1;
ll visited[100001];
 
bool dijkstra(int m)
{
    fill(visited, visited + N + 1111111111111111);
    priority_queue<pair<ll, int>vector<pair<ll,int>>, greater<pair<ll,int>>> pq;
 
    pq.push({ 0,A });
 
    while (!pq.empty()) {
        const ll cost = pq.top().first;
        const int cur = pq.top().second;
        pq.pop();
 
        if (cost > C) continue;
 
        if (cur == B) {
            return true;
        }
 
        if (visited[cur] < cost) continue;
        visited[cur] = cost;
 
        for (auto& next : list[cur]) {
            if (visited[next.second] > cost + next.first && next.first <= m) {
                visited[next.second] = cost + next.first;
                pq.push({ cost + next.first, next.second });
            }
        }
    }
 
    return false;
}
 
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
 
    cin >> N >> M >> A >> B >> C;
    s = 1;
 
    for (int i = 0; i < M; i++) {
        int u, v, w;
        cin >> u >> v >> w;
        list[u].push_back({ w,v });
        list[v].push_back({ w,u });
        e = max(e, w);
    }
 
    while (s <= e) {
        int m = (s + e) / 2;
 
        if (dijkstra(m)) {
            ans = m;
            e = m - 1;
        }
        else {
            s = m + 1;
        }
    }
 
    cout << ans;
}
cs
반응형

+ Recent posts