문제 출처 : https://www.acmicpc.net/problem/13549

 

<C++Code>

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
#include<iostream>
#include<queue>
#define MAX 100001
using namespace std;
int n,m;
int v[MAX];
queue<pair<int,int> > q;
int cnt;
 
int bfs(int start)
{
    q.push({0,start});
    v[start]=1;
    
    while(!q.empty())
    {
        int size=q.size();
        for(int i=0;i<size;i++)
        {
            int po=q.front().second;
             cnt=q.front().first;
             q.pop();
         
    
        if(po==m)
        {
            cout<<cnt<<endl;
        exit(0);
        }
            
        
        int next=po*2;
        while(next<=100000&&v[next]==0)
        {
            q.push({cnt,next});
            v[next]=1;    
        }
    
        next=po-1;
        if(next>=0&&v[next]==0)
        {
            q.push({cnt+1,next});
            v[next]=1;
        }
        next=po+1;
        if(next<=100000&&v[next]==0)
        {
            q.push({cnt+1,next});
            v[next]=1;
        }
}
    }
}
 
 
 
int main(void)
{cin>>n>>m;
bfs(n);
cout<<cnt<<endl;
    return 0;
    
}
cs
c

<C++Code>

 

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
#include<iostream>
#include<queue>
#include<string.h>
#define max 100001
using namespace std;
queue<int> q;
queue<int> w;
int v[max];
bool c[max];
 
int main(void)
{
    int n,m;
    cin>>n>>m;
    memset(v,-1,sizeof(v));
    q.push(n);
    v[n]=0;
    c[n]=true;
    while(!q.empty())
    {
        int x=q.front();
        q.pop();
        //cout<<x<<' ';
        if(x==m)
        {
            break;
        }
        int next=x*2;
        if(!c[next]&&next<=100000)
        {
            q.push(next);
            v[next]=v[x];
            c[next]=true;
            
        }
        next=x-1;
        if(!c[next]&&next>=0)
        {
            w.push(next);
            v[next]=v[x]+1;
            c[next]=true;
            
        }
        next=x+1;
        if(!c[next]&&next<=100000)
        {
            w.push(next);
            v[next]=v[x]+1;c[next]=true;
            
        }
        if(q.empty())
        {
            q=w;
            w=queue<int> ();
            
        }
    }
    cout<<v[m]<<' ';
    
    
    return 0;
    
}
cs

'백준 온라인 저지 > BFS, DFS (그래프)' 카테고리의 다른 글

1707번_이분그래프  (0) 2019.12.14
12851번_숨바꼭질 2  (0) 2019.12.03
13913번_숨바꼭질 4(Bfs)  (0) 2019.12.02
1697번_숨바꼭질(Bfs)  (0) 2019.12.02
7576번_토마토 (Bfs)  (0) 2019.11.27

+ Recent posts