Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <queue>
- using namespace std;
- queue<int> q;
- int dist[100001];
- bool check[100001];
- int A, B, N, M;
- bool isInB(int n) {
- if(n >= 0 && n <= 100000)
- return true;
- else
- return false;
- }
- void pushNext(int now) {
- int nextDist = dist[now] + 1;
- if(isInB(now+1))
- if(!check[now+1]) {
- q.push(now+1);
- dist[now+1] = nextDist;
- check[now+1] = true;
- }
- if(isInB(now-1))
- if(!check[now-1]) {
- q.push(now-1);
- dist[now-1] = nextDist;
- check[now-1] = true;
- }
- if(isInB(now+A))
- if(!check[now+A]) {
- q.push(now+A);
- dist[now+A] = nextDist;
- check[now+A] = true;
- }
- if(isInB(now-A))
- if(!check[now-A]) {
- q.push(now-A);
- dist[now-A] = nextDist;
- check[now-A] = true;
- }
- if(isInB(now+B))
- if(!check[now+B]) {
- q.push(now+B);
- dist[now+B] = nextDist;
- check[now+B] = true;
- }
- if(isInB(now-B))
- if(!check[now-B]) {
- q.push(now-B);
- dist[now-B] = nextDist;
- check[now-B] = true;
- }
- if(isInB(now*A))
- if(!check[now*A]) {
- q.push(now*A);
- dist[now*A] = nextDist;
- check[now*A] = true;
- }
- if(isInB(now*B))
- if(!check[now*B]) {
- q.push(now*B);
- dist[now*B] = nextDist;
- check[now*B] = true;
- }
- }
- int main()
- {
- cin >> A >> B >> N >> M;
- check[N] = true;
- dist[N] = 0;
- q.push(N);
- while(!q.empty()) {
- int now = q.front(); q.pop();
- if(now == M)
- break;
- pushNext(now);
- }
- cout << dist[M] << endl;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement