先判断n和m属于哪一横行
在判断n和m在哪一左斜列和哪一右斜列
然后分别作差求和
#include <iostream> #include <cstdio> #include <cstring> #include <cmath> using namespace std; int fabs(int x) { if(x<0) return -x; return x; } int main() { int i,j,k,ln,lm,rn,rm,n,m; while (cin >> n >> m) { int cn = ceil(sqrt(n)); int cm = ceil(sqrt(m)); rm = (m - (cm - 1)*(cm - 1) - 1)/2+1; rn = (n - (cn - 1)*(cn - 1) - 1)/2+1; lm = (cm*cm - m)/2+1; ln = (cn*cn - n)/2+1; k = fabs(cm - cn) + fabs(lm - ln) + fabs(rm - rn); cout<<k<<endl; } }