fork download
  1. #include<stdio.h>
  2. #include<deque>
  3.  
  4. using namespace std;
  5.  
  6. int dist[121][121];
  7. deque<int>qx, qy;
  8. int X, Y;
  9. void push(int x, int y,int bx,int by) {
  10. if (y > Y)x += y - Y, y = Y;
  11. if (x > X)y += x - X, x = X;
  12. if (dist[x][y])return;
  13. qx.push_back(x); qy.push_back(y);
  14. dist[x][y] = dist[bx][by] + 1;
  15. }
  16. int jd(int x) { if (x < 0)return -x; return x; }
  17. int main() {
  18. int k, m;
  19. scanf("%d%d%d%d", &X, &Y, &k, &m);
  20. qx.push_back(0);qy.push_back(0);
  21. dist[0][0] = 1;
  22. while (!qx.empty()) {
  23. int x = qx.front(); qx.pop_front();
  24. int y = qy.front(); qy.pop_front();
  25. push(x, 0, x, y), push(0, y, x, y);
  26. push(0, x + y, x, y), push(x + y, 0, x, y);
  27. push(x, Y, x, y), push(X, y, x, y);
  28. }
  29. int ans = 1e9;
  30. for (int i = 0; i <= X; i++) for (int j = 0; j <= Y; j++) {
  31. if (dist[i][j] && dist[i][j] <= k + 1 && ans > jd(m - (i + j)))ans = jd(m - (i + j));
  32. }
  33. printf("%d", ans);
  34. return 0;
  35. }
Success #stdin #stdout 0s 4392KB
stdin
14 50 2 32
stdout
18