1219. 移动距离(水题,向上取整公式)
题目链接:
https://www.acwing.com/problem/content/1221/
题解:
对于分子分母都是整数的除法,例如a/b,除了可以用ceil()函数向上取整外,还可以直接用公式(a+b-1)/b;
代码:
#include <algorithm> #include <iostream> using namespace std; int w,m,n; int main(){ cin >> w >> m >> n; int row1,cow1; row1 = (m + w -1) / w; if(row1 % 2 == 1){ if(m % w == 0) cow1 = w; else cow1 = m % w; }else{ if(m % w == 0) cow1 = 1; else cow1 = w - (m % w) + 1; } int row2 = (n+w-1) / w,cow2; if(row2 % 2 == 1){ if(n % w == 0) cow2 = w; else cow2 = n % w; }else{ if(n % w == 0) cow2 = 1; else cow2 = w - (n % w) + 1; } int res = max(row1,row2) - min(row1,row2) + (max(cow1,cow2)-min(cow1,cow2)); cout << res << endl; return 0; }