列表

详情


NC222492. [USACOFeb2020S]Triangles

描述

Farmer John would like to create a triangular pasture for his cows.
There are N fence posts (3≤N≤105) at distinct points (X1,Y1)…(XN,YN) on the 2D map of his farm. He can choose three of them to form the vertices of the triangular pasture as long as one of the sides of the triangle is parallel to the x-axis and another side is parallel to the y-axis.

What is the sum of the areas of all possible pastures that FJ can form?

输入描述

The first line contains N.
Each of the next N lines contains two integers Xi and Yi, each in the range −104…104 inclusive, describing the location of a fence post.

输出描述

As the sum of areas is not necessarily be an integer and may be very large, output the remainder when two times the sum of areas is taken modulo 109+7.

示例1

输入:

4
0 0
0 1
1 0
1 2

输出:

3

说明:

Fence posts (0,0), (1,0), and (1,2) give a triangle of area 1, while (0,0), (1,0), and (0,1) give a triangle of area 0.5. Thus, the answer is 2⋅(1+0.5)=3.

原站题解

上次编辑到这里,代码来自缓存 点击恢复默认模板

C++ 解法, 执行用时: 107ms, 内存消耗: 7800K, 提交时间: 2022-06-26 13:55:35

// USACO 2020 Feb S. Triangles
#include <bits/stdc++.h>
using namespace std;
const int MOD = 1e9 + 7, CC = 1e4;
#define _for(i, a, b) for (int i = (a); i < (int)(b); ++i)
using LL = long long;
struct Item {
  int v, i;
  bool operator<(const Item& x) const {
    if (v != x.v) return v < x.v;
    return i < x.i;
  }
};
int main() {
  int n;
  cin >> n;
  map<int, vector<Item>> XY, YX;
  for (int i = 0, x, y; i < n; i++)
    cin >> x >> y, XY[x + CC].push_back({y, i}), YX[y + CC].push_back({x, i});
  vector<LL> hs(n), bs(n);
  for (auto& p : XY) {
    auto& Y = p.second;
    int sz = Y.size();
    sort(Y.begin(), Y.end());
    hs[Y[0].i] = 0;
    _for(j, 1, sz) hs[Y[0].i] += Y[j].v - Y[0].v;
    _for(j, 1, sz) hs[Y[j].i] =
        hs[Y[j - 1].i] + (2 * j - sz) * (Y[j].v - Y[j - 1].v);
  }
  for (auto& p : YX) {
    auto& X = p.second;
    int sz = X.size();
    sort(X.begin(), X.end());
    bs[X[0].i] = 0;
    _for(j, 1, sz) bs[X[0].i] += X[j].v - X[0].v;
    _for(j, 1, sz) bs[X[j].i] =
        bs[X[j - 1].i] + (2 * j - sz) * (X[j].v - X[j - 1].v);
  }
  LL ans = 0;
  _for(i, 0, n)(ans += hs[i] * bs[i] % MOD) %= MOD;
  cout << ans << '\n';
}

上一题