Thursday 27 October 2016

Spoj ELEVTRBL

You can read problem here

Logic:

First of all we will try brute force solution because we can do this better than anyone. ;)
So brute force solution will be simple recursion function where on each floor we have 2 choices
1. Go Up if we can
2. Go Down if we can
so our code will look like

Function(step) {
          IF step + UpJump <= HighestFloor:
               Function(step + UpJump)
         
          IF step - Down > 0:
               Function(step - Down)
}

Now here question is how we can halt this recursion so this question is easy if we already visited this floor that mean we traverse a loop and come back again so no need to go further, here we can use Vis array for this information that we already visited or not.
Now here again we will get in stuck because of memory issue first think why we will stuck here and then think solution also. :P


Below code you can see also

#include <iostream>
#include <sstream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <cctype>
#include <string>
#include <vector>
#include <list>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <algorithm>
#include <functional>
using namespace std; 
#define DEBUG(x) cout << '>' << #x << ':' << x << endl;
#define REP(i,n) for(int i=0;i<(n);i++)
#define FOR(i,a,b) for(int i=(a);i<=(b);i++)
#define FORD(i,a,b) for(int i=(a);i>=(b);i--)
inline bool EQ(double a, double b) { return fabs(a-b) < 1e-9; }
const int INF = 1<<29;
typedef long long ll;
inline int two(int n) { return 1 << n; }
inline int test(int n, int b) { return (n>>b)&1; }
inline void set_bit(int & n, int b) { n |= two(b); }
inline void unset_bit(int & n, int b) { n &= ~two(b); }
inline int last_bit(int n) { return n & (-n); }
inline int ones(int n) { int res = 0; while(n && ++res) n-=n&(-n); return res; }
template<class T> void chmax(T & a, const T & b) { a = max(a, b); }
template<class T> void chmin(T & a, const T & b) { a = min(a, b); }
/////////////////////////////////////////////////////////////////////

int Limit;
int Start;
int Goal;
int Up;
int Down;

bool Vis[1000006];
int Dis[1000006];

void bfs(int vertex, int depth) {
Vis[vertex] = true;
Dis[vertex] = depth;
queue<int> Q;
Q.push(vertex);
while(!Q.empty()) {
vertex = Q.front();
Q.pop();
if(vertex == Goal) return;
if(vertex + Up <= Limit && !Vis[vertex + Up]) {
Q.push(vertex + Up);
Dis[vertex + Up] = Dis[vertex] + 1;
Vis[vertex + Up] = true;
}
if(vertex - Down > 0 && !Vis[vertex - Down]) {
Q.push(vertex - Down);
Dis[vertex - Down ] = Dis[vertex] + 1;
Vis[vertex - Down ] = true;
}
}
}

int main()
{
scanf("%d%d%d%d%d", &Limit, &Start, &Goal, &Up, &Down);
bfs(Start, 0);
if(Vis[Goal]) {
printf("%d\n", Dis[Goal]);
} else {
printf("use the stairs\n");
}
    return 0;
}


No comments:

Post a Comment