Tree's a Crowd
Tree's a Crowd |
Dr William Larch, noted plant psychologist and inventor of the phrase``Think like a tree--Think Fig'' has invented a new classificationsystem for trees. This is a complicated system involving a series ofmeasurements which are then combined to produce three numbers (in therange [0, 255]) for any given tree. Thus each tree can be thought ofas occupying a point in a 3-dimensional space. Because of the natureof the process, measurements for a large sample of trees are likely tobe spread fairly uniformly throughout the whole of the availablespace. However Dr Larch is convinced that there are relationships tobe found between close neighbours in this space. To test thishypothesis, he needs a histogram of the numbers of trees that haveclosest neighbours that lie within certain distance ranges.
Write a program that will read in the parameters of up to 5000 treesand determine how many of them have closest neighbours that are lessthan 1 unit away, how many with closest neighbours 1 or more but lessthan 2 units away, and so on up to those with closest neighbours 9 ormore but less than 10 units away. Thus if is thedistance between the i'th point and its nearest neighbour(s) and
, withj and k integers and k = j+1, thenthis point (tree) will contribute 1 to the j'th bin in the histogram(counting from zero). For example, if there were only two points 1.414units apart, then the histogram would be 0, 2, 0, 0, 0, 0, 0, 0, 0, 0.
Input and Output
Input will consist of aseries of lines, each line consisting of 3 numbers in the range [0,255]. The file will be terminated by a line consisting of threezeroes.
Output will consist of a single line containing the 10 numbersrepresenting the desired counts, each number right justified in afield of width 4.
Sample input
10 10 0
10 10 0
10 10 1
10 10 3
10 10 6
10 10 10
10 10 15
10 10 21
10 10 28
10 10 36
10 10 45
0 0 0
Sample output
2 1 1 1 1 1 1 1 1 1
这道题大意就是给予n个点的三维坐标,然后求出各点到其他坐标的最短距离,然后将最短距离在0到9之内的各点的个数输出。
PS:计算两点间的距离时,是要四舍五入的,开始时我都是按照小数进一来做的,结果WA了几次。
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdio>
#include <cmath>
using namespace std;
const int N = 5100;
const int INF = 1 << 29;
struct Node {
double x;
double y;
double z;
}p[N];
int d;
int n[20];
int main() {
memset(p,0,sizeof(p));
memset(n,0,sizeof(n));
double p_x;
double p_y;
double p_z;
int t;
for (t = 0; t < 5000; t++) {
cin >> p_x >> p_y >> p_z;
if (!p_x && !p_y && !p_z)
break;
p[t].x = p_x;
p[t].y = p_y;
p[t].z = p_z;
}
for (int i = 0; i < t; i++) {
d = INF;
for (int j = 0; j < t; j++) {
if (i != j) {
int tmp = (int)sqrt(pow(p[i].x-p[j].x,2)+pow(p[i].y-p[j].y,2)+pow(p[i].z-p[j].z,2));
if (d > tmp)
d = tmp;
}
}
d = (d + 0.5);
if (d < 10)
n[d]++;
}
for (int i = 0; i < 10; i++)
printf("%4d",n[i]);
cout << endl;
return 0;
}