很考验细心的一道题。把各种情况分析清楚了,就不难写出对的程序了。
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <vector>
#include <list>
#include <queue>
#include <map>
#include <set>
#include <stack>
#include <assert.h>
#include <algorithm>
#include <math.h>
#include <ctime>
#include <functional>
#include <string.h>
#include <stdio.h>
#include <numeric>
#include <float.h>
using namespace std;
struct Point {
int x, y;
Point(int ax, int ay) : x(ax), y(ay) {}
};
int getRow(long long index) {
long long r = sqrt(index);
if (r * r == index) {
return r;
}
else return r + 1;
}
Point getPoint(long long index) {
int row = getRow(index);
int lastRow = row - 1;
int col = index - lastRow * lastRow;
return Point(row, col - row);
}
int main() {
long long e1, e2;
double a = sqrt(3) / 3 / 2;
double b = sqrt(3) / 3;
while (cin >> e1) {
cin >> e2;
if (e1 > e2) {
long long t = e2;
e2 = e1;
e1 = t;
}
Point p1 = getPoint(e1 + 1);
Point p2 = getPoint(e2 + 1);
double l = ((double)llabs(p1.y - p2.y)) / 2;
double h;
double h1 = 0, h2 = 0, h3 = 0;
if (p2.x > p1.x) {
if ((p1.x + p1.y) % 2 == 0) {
h1 = b;
}
else {
h1 = a;
}
if ((p2.x + p2.y) % 2 == 0) {
h2 = a;
}
else {
h2 = b;
}
h3 = (p2.x - p1.x - 1) * sqrt(3) / 2;
h = h1 + h2 + h3;
}
else {
if (abs(p1.y % 2) == abs(p2.y % 2)) {
h = 0;
}
else {
h = sqrt(3) / 6;
}
}
printf("%.3f\n", sqrt((l * l + h * h)));
}
return 0;
}