152 - Tree's a Crowd

题意:
每一颗树都与其他的树计算距离, 取最近距离(下取整). 如果最近距离在 [1,9] 之间, 就记录下来. 最后输出各个最近距离的个数, 即最近距离为 1 的个数, 最近距离为 2 的个数...最近距离为 9 的个数.

思路:
见题意.

要点:
1. 使用 sqrt 开根号.
2. 使用 pow(a, 2) 计算 a 的平方.
3. printf("%4d", histogram[i]); 输出宽度为4的整数, 右对齐.
4. 最大整数为 numeric_limits<int>::max().

题目:
http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=98&page=show_problem&problem=88

代码:

# include <iostream>
# include <string>
# include <cstdio>
# include <cstring>
# include <vector>
# include <algorithm>
# include <cctype>
# include <iterator>
# include <assert.h>
# include <cmath>
# include <limits>  // numeric_limits
using namespace std;

// sqrt 开根号
// pow 求平方
// 区间是左闭右开, 即 [0, 1), [1, 2)...
// C++ 最大整数

int main(int argc, char const *argv[])
{
  #ifndef ONLINE_JUDGE
    freopen("152_i.txt", "r", stdin);  
    freopen("152_o.txt", "w", stdout); 
  #endif
  
  vector<int> xs;
  vector<int> ys;
  vector<int> zs;

  int x;
  int y; 
  int z;

  while (!cin.eof()) {
    cin >> x >> y >> z;
    if (x==0 && y==0 && z==0)
      break;

    xs.push_back(x);
    ys.push_back(y);
    zs.push_back(z);
  }

  const int numPoint = xs.size();
  vector<int> histogram(10, 0);   // histogram 初始化为 10 个 0

  // 每个节点都和其他节点计算距离,取最小距离
  for (int i=0; i<numPoint; i++) {
    unsigned long int min = numeric_limits<int>::max();

    for (int j=0; j<numPoint; j++) {
      if (i != j) {
        long distance = int(sqrt(pow(xs[i]-xs[j], 2) + 
                                 pow(ys[i]-ys[j], 2) +
                                 pow(zs[i]-zs[j], 2)));
        min = distance < min ? distance : min;
      }
    }

    if (min >=0 && min < 10) {
      histogram[min] = histogram[min] + 1;
    }
  }
  
//copy(histogram.begin(), histogram.end(), ostream_iterator<int>(cout, "    "));
  for (int i=0; i<10; i++) {
    printf("%4d", histogram[i]);    // 每个输出宽度为 4, 不是接 4 个空格
  }
  cout << endl;                     // 最后要输出一个空行,否则WA

  return 0;
}

环境: C++ 4.5.3 - GNU C++ Compiler with options: -lm -lcrypt -O2 -pipe -DONLINE_JUDGE

你可能感兴趣的:(tree,152,Crowd)