题目:
Connect the countless points with lines, till we reach the faraway yonder.
There are n points on a coordinate plane, the i-th of which being (i, yi).
Determine whether it's possible to draw two parallel and non-overlapping lines, such that every point in the set lies on exactly one of them, and each of them passes through at least one point in the set.
The first line of input contains a positive integer n (3 ≤ n ≤ 1 000) — the number of points.
The second line contains n space-separated integers y1, y2, ..., yn ( - 109 ≤ yi ≤ 109) — the vertical coordinates of each point.
Output "Yes" (without quotes) if it's possible to fulfill the requirements, and "No" otherwise.
You can print each letter in any case (upper or lower).
5
7 5 8 6 9
Yes
5
-1 -2 0 0 -5
No
5
5 4 3 2 1
No
5
1000000000 0 0 0 0
Yes
题目大意:给定N个点,问是否存在两条平行且不重叠的直线让所有点分别落在两条直线上。
分析:首先这个问题分为两种情况,一种是一条直线有一个点,另一条直线覆盖了其余所有点;另一种情况是每条直线至少覆盖两个点。对于第一种情况,我们只要枚举每一个点,然后从剩余的点中任取两个点,然后判断是否满足条件;对于第二种情况,我们首先不重复的枚举任意两点构成直线的斜率,再利用一个map对斜率进行计数。最终我们将出现次数大于等于两次的斜率进行检查。
检查斜率时,取出每一个这样的斜率然后带入所有的点,统计截距的个数,如果等于2,那么满足条件,否则不满足。
代码:
#include <bits/stdc++.h> using namespace std; const int maxn = 1005; int n, y[maxn]; struct Point { int x, y; Point() {} Point(int x, int y) { this->x = x; this->y = y; } }; vector<double> check; map<double, int> cnt, num; int main() { check.clear(); cnt.clear(); scanf("%d", &n); for(int i = 1; i <= n; i++) { scanf("%d", &y[i]); } for(int i = 1; i <= n; i++) { int a = (i + 1) % n; int b = (i + 2) % n; bool tag = true; for(int j = 1; j <= n; j++) { if(j != i) { int tx = j, ty = y[j]; if((y[a] - y[b]) * tx + (b - a) * ty + a * y[b] - b * y[a] != 0) { tag = false; break; } } } if((y[a] - y[b]) * i + (b - a) * y[i] + a * y[b] - b * y[a] == 0) { tag = false; } if(tag) { printf("Yes\n"); return 0; } } for(int i = 1; i <= n - 1; i++) { for(int j = i + 1; j <= n; j++) { double k = (double)(y[j] - y[i]) / (double)(j - i); cnt[k]++; if(cnt[k] == 2) { check.push_back(k); } } } for(int i = 0; i < check.size(); i++) { num.clear(); double k = check[i]; int sum = 0; for(int j = 1; j <= n; j++) { double tb = (double)y[j] - k * (double)j; num[tb]++; if(num[tb] == 1) { sum++; if(sum > 2) { break; } } } if(sum == 2) { printf("Yes\n"); return 0; } } printf("No\n"); return 0; }