ACM: Nearest Numbers
Description
Given three integer sequences which have been sorted in ascending order,pick one integer from each sequence and we can get three integers.we want these three integers to be nearest to each other.Assuming these three integers as a,b,c, they are nearest to each other means d=(a-b)2+(b-c)2+(c-a)2 is the smallest.
Input
There are many test cases. For each test case,the first line are three integers la,lb,lc, they let you know the length of each sequence. The following three lines separately have la,lb,lc integers,give you the integers in each sequence. 1<=la,lb,lc<=10^6 and All integers in the sequences are in the range of [-10^9,10^9].
Output
For each test case, just print one integer : the smallest d as mentioned above.
Sample Input
10 10 10 1 2 3 4 5 6 7 8 9 10 2 3 6 8 10 12 14 16 18 20 3 5 7 9 11 12 14 16 18 20
Sample Output
0
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
const int maxn = 1 << 20;
typedef long long LL;
LL a[maxn], b[maxn], c[maxn];
inline LL min(LL x, LL y)
{return x < y ? x : y;}
inline LL cal(LL x, LL y, LL z)
{return (x - y) * (x - y) + (x - z) * (x - z) + (z - y) * (z - y);}
int main()
{
LL ans, tmpa, tmpb, tmpc;
int n1, n2, n3, i, j, k;
// freopen("hehe.txt", "r", stdin);
while(scanf("%d%d%d", &n1, &n2, &n3) != EOF)
{
for(i = 0; i < n1; ++ i) scanf("%lld", &a[i]);
for(i = 0; i < n2; ++ i) scanf("%lld", &b[i]);
for(i = 0; i < n3; ++ i) scanf("%lld", &c[i]);
ans = ((LL)1 << 63) - 1;
i = j = k = 0;
while(i < n1 && j < n2 && k < n3 && ans > 0)
{
ans = min(ans, cal(a[i], b[j], c[k]));
tmpa = cal(a[i + 1], b[j], c[k]);
tmpb = cal(a[i], b[j + 1], c[k]);
tmpc = cal(a[i], b[j], c[k + 1]);
if(tmpa < tmpb && tmpa < tmpc) ++ i;
else if(tmpb < tmpc) ++ j;
else ++ k;
}
printf("%lld\n", ans);
}
return 0;
}