AtCoder Grand Contest 008 A - Simple Calculator
問題について考えたこと
数直線上の、xとyの位置で分岐して処理をしたました。
xは正の方向にしか進めません。解説のようにするのが正しいです。
#define _GIBCXX_DEBUG #include <bits/stdc++.h> using namespace std; #define rep(i, n) for (int i = 0; i < (n); ++i) #define all(v) v.begin(), v.end() using namespace std; using ll = long long; int main(void) { int x, y; cin >> x >> y; int ans = 0; if (0 <= x && 0 <= y) { if (x < y) { ans = y - x; } else { ans = x - y + 1; if (y != 0) ++ans; } } else if (x < 0 && y <= 0) { if (x < y) { ans = abs(x) - abs(y); } else { ans = abs(y) - abs(x) + 2; } } else if (x < 0 && 0 < y) { if (y < abs(x)) { ans = abs(x) - y + 1; } else { ans = y - abs(x) + 1; } } else if (0 <= x && y < 0) { if (x < abs(y)) { ans = abs(y) - x + 1; } else { ans = x - abs(y) + 1; } } cout << ans << endl; return 0; }
解説を読みました。
#define _GIBCXX_DEBUG #include <bits/stdc++.h> using namespace std; #define rep(i, n) for (int i = 0; i < (n); ++i) #define all(v) v.begin(), v.end() using namespace std; using ll = long long; template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; } int main(void) { int x, y; cin >> x >> y; int ans = 1000000010; // Aのみ if (x <= y) chmin(ans, y - x); // xの符号を反転してもyより小さいなら、反転してA if (-x <= y) chmin(ans, y + x + 1); // yの絶対値がxより大きく、yが負であるならxはAして反転 if (x <= -y) chmin(ans, -y - x + 1); // xとyが共に負であり、絶対値が|y|>|x|ならばxは反転してAして反転 if (-x <= -y) chmin(ans, -y - (-x) + 2); cout << ans << endl; return 0; }