fork download
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. #define pii pair<int, int>
  6. #define f first
  7. #define s second
  8. #define pb push_back
  9. int const NMAX = 100;
  10. int X, Y, K, M;
  11. int moves[1 + NMAX][1 + NMAX];
  12.  
  13. void bfs() {
  14. queue<pii> q;
  15. q.push({0, 0});
  16. while(!q.empty()) {
  17. pii from = q.front();
  18. q.pop();
  19. if(moves[from.f][from.s] == K) continue;
  20. vector<pii> v;
  21. v.pb({0, from.s}); v.pb({X, from.s});
  22. v.pb({from.f, 0}); v.pb({from.f, Y});
  23. v.pb({min(X, from.f+from.s), max(0, from.s+from.f-X)});
  24. v.pb({max(0, from.s+from.f-Y), min(Y, from.f+from.s)});
  25. for(auto p : v) {
  26. if(moves[p.f][p.s] == 0) {
  27. moves[p.f][p.s] = moves[from.f][from.s] + 1;
  28. q.push(p);
  29. }
  30. }
  31. }
  32. }
  33.  
  34. int main() {
  35. cin >> X >> Y >> K >> M;
  36. bfs();
  37. int ans = M;
  38. for(int i = 0; i <= X; i++) {
  39. for(int j = 0; j <= Y; j++) {
  40. if(moves[i][j] != 0) {
  41. ans = min(ans, abs(i+j-M));
  42. }
  43. }
  44. }
  45. cout << ans << "\n";
  46. return 0;
  47. }
Success #stdin #stdout 0.01s 5280KB
stdin
5 8 4 11
stdout
1