UVA270 Lining Up 题解
UVA270 Lining Up 题解
呵呵,目前最优解。
题意
就是给你一些点,问你画一条直线,最多可以经过多少点。注意,2 个输出间要有一个空行,最后一个输出后也应有一个空行。
时间复杂度 O(n^3) 做法
众所周知,两点可以确定一条直线。那么我们只需要枚举一条线上的某
枚举
#include <bits/stdc++.h>
using namespace std;
const int N = 710;
int x[N], y[N], n, T;
inline int check(int i, int j, int k) { return 1ll * (x[j] - x[i]) * (y[k] - y[i]) == 1ll * (x[k] - x[i]) * (y[j] - y[i]); }
void solve() {
int cnt = 1, ans = 0;
for (int i = 1; i <= n; i++)
for (int j = i + 1; j <= n; j++) {
cnt = 1;
for (int k = 1; k <= n; k++) {
if (k == i) continue;
if ((x[k] == x[i] && y[k] == y[i]) || check(i, j, k)) ++cnt;
}
ans = max(ans, cnt);
}
printf("%d\n", ans);
if (T) printf("\n");
}
char str[N];
void read() {
n = 0;
do ++n, cin.getline(str, N);
while (sscanf(str, "%d %d", &x[n], &y[n]) == 2);
--n;
}
int main() {
cin >> T, cin.getline(str, N), cin.getline(str, N);
while(T--) read(), solve();
return 0;
}
时间复杂度 O(n^2 \log n) 做法
我们发现在以上做法中,一个点最多会被我们所枚举的
我们可以枚举一个点
这种做法其实可以用哈希表优化至
#include <bits/stdc++.h>
using namespace std;
const int N = 710;
int x[N], y[N], n, T;
double s[N];
inline bool eq(double a, double b) { return abs(a - b) <= (1e-8); }
void solve() {
int cnt = 1, tot, nowcnt, pot = 0, ans = 0;
for (int i = 1; i <= n; i++) {
tot = 0, cnt = 0, pot = 0;
for (int j = 1; j <= n; j++) {
if (x[i] == x[j] && y[i] == y[j]) {
++pot;
continue;
}
s[++tot] = double(y[j] - y[i]) / (x[j] - x[i]);
}
sort(s + 1, s + tot + 1), nowcnt = 0, s[tot + 1] = -123456789;
for (int i = 1; i <= tot; i++) {
if (s[i] == s[i + 1])
++nowcnt;
else
ans = max(ans, nowcnt + 1), nowcnt = 0;
}
}
printf("%d\n", ans + pot);
if (T) printf("\n");
}
char str[N];
void read() {
n = 0;
do ++n, cin.getline(str, N);
while (sscanf(str, "%d %d", &x[n], &y[n]) == 2);
--n;
}
int main() {
cin >> T, cin.getline(str, N), cin.getline(str, N);
while (T--) read(), solve();
return 0;
}