Author : Anwar Jahid Ruman Hossain CSE, Batch - 6 BRUR. Problem Statement : [ URI ] 1910 - Help Clotilde Source : URI Online Judge Category : Graph Theory Algorithm : BFS Verdict : Accepted
- #include<bits/stdc++.h>
- using namespace std;
- #define ll long long int
- #define mx 100000
- #define inf 1<<30
- #define endl '\n'
- int channels[mx+5];
- int mov[mx+5];
- bool isValid(int id,int cnt){
- if(id>=1 && id<=mx && channels[id]==1 && cnt<mov[id]){
- mov[id]=cnt;
- return true;
- }
- return false;
- }
- int bfs(int o,int d){
- queue<pair<int,int> >q;
- pair<int,int>s;
- s.first=o;
- s.second=0;
- q.push(s);
- mov[s.first]=0;
- while(!q.empty()){
- pair<int,int>a=q.front();
- q.pop();
- if(a.first==d)return a.second;
- if(isValid(a.first+1,a.second+1))q.push(make_pair(a.first+1,a.second+1));
- if(isValid(a.first-1,a.second+1))q.push(make_pair(a.first-1,a.second+1));
- if(isValid(a.first*3,a.second+1))q.push(make_pair(a.first*3,a.second+1));
- if(isValid(a.first*2,a.second+1))q.push(make_pair(a.first*2,a.second+1));
- if(a.first%2==0){
- if(isValid(a.first/2,a.second+1))q.push(make_pair(a.first/2,a.second+1));
- }
- }
- return -1;
- }
- int main(){
- // freopen("input.txt","r",stdin);
- //freopen("output.txt","w",stdout);
- int o,d,k,banned;
- while(cin>>o>>d>>k){
- if(o==0 && d==0 && k==0)break;
- for(int i=1;i<=mx;i++){
- channels[i]=1;
- mov[i]=inf;
- }
- while(k--){
- cin>>banned;
- channels[banned]=0;
- }
- cout<<bfs(o,d)<<endl;
- }
- return 0;
- }
Channels[1-mx]=1
mov[1-mx]= INF
channels[4,5]=0
bfs(o,d) = bfs(3,8)
pair -> (3,0) mov[3]=0
|
|
|
||||||||||||||||||||||||||||||||||||||||||||
Queue
|
+1
|
-1
|
*3
|
*2
|
/2
|
Next Queue
|
(3,0)
|
(2,1)
|
(9,1)
|
(6,1)
|
(2,1)
|
||
(2,1)
|
(3,2)
|
(1,2)
|
(6,2)
|
(1,2)
|
(9,1)
|
|
(9,1)
|
(10,2)
|
(8,2)
|
Break target channel d==8 so required move is 2
|
Approach:
1. Valid channel এর value
1 সেট করি। এবং Invalid channel এর value 0 সেট করি।
2. Mov[
] এর সব index এর value INF সেট করি।
3. BFS
এ current channel এবং starting mov Zero pair হিসেবে কিউ q তে পুশ করি।
4. (+1,-1,*3,*2,/2)
এর জন্য প্রতিবার valid mov নিয়ে q কিউ তে update করি যতক্ষণ না target channel d না পাই , d পেলে এর জন্য প্রাপ্ত mov রিটার্ন করি। এটাই Required Output.
No comments:
Post a Comment