본문 바로가기
알고리즘/DFS

17412 도시 왕복하기 1

by tryotto 2019. 8. 22.
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
#include <stdio.h>
#include <vector>
#include <queue>
#include <algorithm>
 
using namespace std;
 
vector<vector<int> > adj(405);
 
int cost[405][405= { 0 };
int flow[405][405= { 0 };
 
int main() {
    int n, p, rst = 0;
    scanf("%d %d"&n, &p);
 
    while (p--) {
        int a, b;
        scanf("%d %d"&a, &b);
 
        cost[a][b] = 1;
        adj[a].push_back(b);
        adj[b].push_back(a);
    }
 
    while (1) {
        queue<int> q;
        int visit[405= { 0 };
        int prev[405= { 0 };
 
        q.push(1);
        visit[1= 1;
 
        int flag = 0;
        while (q.empty() == false) {
            int cur = q.front();
            q.pop();
            
            if (cur == 2) {
                flag = 1;
                break;
            }
            for (int i = 0; i < adj[cur].size(); i++) {
                int next = adj[cur][i];
 
                if (cost[cur][next] > flow[cur][next] && visit[next] == 0) {
                    visit[next] = 1;
                    prev[next] = cur;
                    q.push(next);
                }
            }
        }
        
        int end = 2;
        int cur = prev[end];
 
        if (flag == 0)
            break;
 
        int minFlow = cost[cur][end- flow[cur][end];
        while (cur != 1) {
            cur = prev[cur];
            end = prev[end];
 
            minFlow = min(minFlow, cost[cur][end- flow[cur][end]);
        }
        
        end = 2;
        cur = prev[end];
        flow[cur][end+= 1;
        flow[end][cur] -= 1;
        while (cur != 1) {
            end = prev[end];
            cur = prev[cur];
            flow[cur][end+= minFlow;
            flow[end][cur] -= minFlow;
        }
        rst += minFlow;
    }
    printf("%d", rst);
}
cs


## 주의점
네트워크 블로우는 반드시, 
역방향 간선에 대해서 adj vector과 cost, flow 배열을 선언해서 계산해줘야 한다

minFlow도 반드시, cost - flow 식을 이용해서 구해야 한다

내 멋대로 하면 절대로 풀리지 않는다

'알고리즘 > DFS' 카테고리의 다른 글

2668 숫자 고르기  (0) 2019.09.03
1991 트리 순회  (0) 2019.08.26
11377 열혈강호3  (0) 2019.08.22
6086 최대 유량  (0) 2019.08.22
11376 열혈강호2  (0) 2019.08.20