POJ 3278 -- Catch That Cow

 POJ 3278 -- Catch That Cownode

 題意:ios

 

給定兩個整數n和k數組

 

經過 n+1或n-1 或n*2 這3種操做,使得n==kspa

 

輸出最少的操做次數code

解題思路:blog

@使用BFS,已經訪問過的數值再也不進行下一層的搜索,使用bool visit[maxn]標記,k最大爲10W,因此設置maxn爲10W+3足矣ci

@進行剪枝 當前要檢索的數值爲n,其下一層的數值有三個取值n-1,n+1,2*n string

  設這個取值爲tempit

  1.temp<0 或者 temp>maxn 越界,則無論它io

    簡單說明一下我對最大值越界的理解吧...若是k=100000,當temp=100020>100003(maxn)應該捨棄,由於如有一個數爲100002,則100002到100000的步數定比100020少。最小值越界同理。

  2.temp已經訪問過,再也不進行處理

 

1)使用STL的queue

 1 #include<iostream>  2 #include<queue>  3 #include<cstring>  4 using namespace std;  5 const int maxn = 100003;  6 int change(int x,int ch)  7 {///0爲x-1,1爲x+1,2爲2*x  8 if(ch == 0)  9 return x-1; 10 if(ch == 1) 11 return x+1; 12 if(ch == 2) 13 return 2*x; 14 } 15 16 struct node{ 17 int num; 18 int deep; 19 node(int num,int deep):num(num),deep(deep){} 20 }; 21 22 bool visit[maxn]; 23 24 int main() 25 { 26 int n,k; 27 while(cin>>n>>k) 28  { 29 queue<node> q; 30 memset(visit,false,sizeof(visit)); 31 node u(n,0); 32  q.push(u); 33 visit[n] = true; 34 int head = 0; 35 int rear = 1; 36 while(!q.empty()) 37  { 38 u = q.front();q.pop(); 39 if(u.num == k) 40  { 41 cout<<u.deep<<endl; 42 break; 43  } 44 for(int i=0;i<3;i++) 45  { 46 int temp = change(u.num,i); 47 if(0<=temp && temp<=maxn && !visit[temp]) 48  { 49 node v(temp,u.deep+1); 50  q.push(v); 51 visit[temp] = true; 52  } 53  } 54  } 55  } 56 return 0; 57 }

 

2)使用數組

 1 #include<iostream>  2 #include<algorithm>  3 #include<cstring>  4 using namespace std;  5 const int maxn = 200030;  6 int change(int x,int ch)  7 {///0爲x-1,1爲x+1,2爲2*x  8 if(ch == 0)  9 return x-1; 10 if(ch == 1) 11 return x+1; 12 if(ch == 2) 13 return 2*x; 14 } 15 16 struct node{ 17 int num; 18 int deep; 19 }; 20 int visit[maxn]; 21 node queue[maxn]; 22 int main() 23 { 24 int n,k; 25 while(cin>>n>>k) 26  { 27 memset(visit,false,sizeof(visit)); 28 queue[0].num = n; 29 queue[0].deep = 0; 30 visit[n] = true; 31 int head = 0; 32 int rear = 1; 33 while(head<rear) 34  { 35 int m = queue[head].num; 36 if(m==k) 37  { 38 cout<<queue[head].deep<<endl; 39 break; 40  } 41 for(int i=0;i<3;i++) 42  { 43 int temp = change(m,i); 44 if(temp>=0 && temp<=maxn && !visit[temp])///進行剪枝 45  { 46 queue[rear].num = temp; 47 queue[rear++].deep = queue[head].deep+1; 48 visit[temp] = true; 49  } 50  } 51 head++; 52  } 53  } 54 return 0; 55 }

相關文章
相關標籤/搜索