How We Coding

### Parametric Search + BFS ###


[1939] 중량제한 : http://boj.kr/1939


<소스코드>


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
#include <cstdio>
#include <vector>
#include <queue>
using namespace std;
 
struct P { int to, limit; };
 
int n, m;
int a, b, c;
vector<P> v[10001];
 
bool isPossible(int mid)
{
 
    queue<int> q;    
    q.push(a);
    
    vector<bool> visited(n+10);
    visited[a] = 1;
 
    while(!q.empty()) {
        int cur = q.front(); q.pop();
 
        for(auto &p : v[cur]) {
            int next = p.to;
            int c = p.limit;
            if(!visited[next] && mid <= c) {
                if(next == b) return true;
                q.push(next);
                visited[next] = 1;
            }
        }
    }
    return false;
}
 
int main()
{
    scanf("%d%d"&n, &m);
 
    while(m--) {
        scanf("%d%d%d"&a, &b, &c);
        v[a].push_back((P){b, c});
        v[b].push_back((P){a, c});
    }
 
    scanf("%d%d"&a, &b);
    
    int s=1, e=1e9;
    while(s <= e) {
        int mid = (s+e)/2;
        if(isPossible(mid)) s = mid+1;
        else e = mid-1;
    }
    printf("%d\n", s-1); 
    return 0;
}
 
cs

>> 중량을 mid 로 설정했을 때, 이게 답이 될 수 있으면 탐색범위를 [mid+1, e] 로 좁혀간다. 

>> 답이될 수 없다면 [s, mid-1] 로 좁힌다.

'BOJ > Parametric Search' 카테고리의 다른 글

[3649] 로봇 프로젝트  (0) 2018.07.24
[13905] 세부 (다른방법으로 풀어보기)  (0) 2018.07.24