题解:P9423 [蓝桥杯 2023 国 B] 数三角

· · 题解

这个问题可以描述为:在一个二维平面上,有若干个点,需要找出这些点中有多少组三点不在一条直线上。

code:

#include <bits/stdc++.h>
using namespace std;
struct Point {
    int x, y;
};
long long f(const Point& p1, const Point& p2) {
    return (long long)(p1.x - p2.x) * (p1.x - p2.x) + (long long)(p1.y - p2.y) * (p1.y - p2.y);
}

bool tt(const Point& p1, const Point& p2, const Point& p3) {
    return (long long)(p2.y - p1.y) * (p3.x - p2.x) == (long long)(p3.y - p2.y) * (p2.x - p1.x);
}

int main() {
    int n;
    cin >> n;
    Point a[2000];
    for (int i = 0; i < n; ++i) {
        cin >> a[i].x >> a[i].y;
    }

    int count = 0;

    for (int i = 0; i < n; ++i) {
        unordered_map<long long, vector<int>> distMap;
        for (int j = 0; j < n; ++j) {
            if (i == j) continue;
            long long distSq = f(a[i], a[j]);
            distMap[distSq].push_back(j);
        }
        for (auto& pair : distMap) {
            const vector<int>& indices = pair.second;
            int m = indices.size();
            if (m >= 2) {
                for (int a = 0; a < m; ++a) {
                    for (int b = a + 1; b < m; ++b) {
                        int j = indices[a];
                        int k = indices[b];
                        if (!tt(a[i], a[j], a[k])) {
                            ++count;
                        }
                    }
                }
            }
        }
    }

    cout << count << endl;
    return 0;
}

通过遍历所有点的组合,计算每组点之间的距离,并利用共线性判断函数来统计不共线的点三元组的数量,从而解决这个问题。