24h購物| | PChome| 登入
2012-04-12 15:46:10| 人氣2,030| 回應0 | 上一篇 | 下一篇

[UVA] 270 - Lining Up

推薦 0 收藏 0 轉貼0 訂閱站台


 Lining Up 

``How am I ever going to solve this problem?" said the pilot.

Indeed, the pilot was not facing an easy task. She had to drop packages at specific points scattered in a dangerous area. Furthermore, the pilot could only fly over the area once in a straight line, and she had to fly over as many points as possible. All points were given by means of integer coordinates in a two-dimensional space. The pilot wanted to know the largest number of points from the given set that all lie on one line. Can you write a program that calculates this number?

Your program has to be efficient!

Input

The input begins with a single positive integer on a line by itself indicating the number of the cases following, each of them as described below. This line is followed by a blank line, and there is also a blank line between two consecutive inputs.
The input consists of N pairs of integers, where 1 < N < 700. Each pair of integers is separated by one blank and ended by a new-line character. The list of pairs is ended with an end-of-file character. No pair will occur twice.

Output

For each test case, the output must follow the description below. The outputs of two consecutive cases will be separated by a blank line.
The output consists of one integer representing the largest number of points that all lie on one line.

Sample Input

1

1 1
2 2
3 3
9 10
10 11

Sample Output

3

窮舉基點之後, 對後每一點拉出斜率, 對這些斜率做排序, 求最長(連續相同)的長度即可
效率 O(n*nlogn)

#include <stdio.h>
#include <stdlib.h>
typedef struct {
int x, y;
}Point;

int cmp(const void *i, const void *j) {
Point *x, *y;
x = (Point *)i, y = (Point *)j;
if(x->x != y->x)
return x->x - y->x;
return x->y - y->y;
}
int gcd(int x, int y) {
if(y == 0) return x;
x = abs(x);
y = abs(y);
int tmp;
while(x%y) {
tmp = x, x = y, y = tmp%y;
}
return y;
}
int main() {
Point D[700];
int t;
char str[100];
scanf("%d", &t);
getchar();
getchar();
while(t--) {
int n = 0;
while(gets(str)) {
if(str[0] == '\0')
break;
sscanf(str, "%d %d", &D[n].x, &D[n].y);
n++;
}
qsort(D, n, sizeof(Point), cmp);
int i, j;
int ans = 1, g;
Point slope[700];
for(i = 0; i < n; i++) {
int m = 0, tmp;
for(j = i+1; j < n; j++) {
slope[m].x = D[i].x - D[j].x;
slope[m].y = D[i].y - D[j].y;
g = gcd(slope[m].x, slope[m].y);
slope[m].x /= g;
slope[m].y /= g;
m++;
}
qsort(slope, m, sizeof(Point), cmp);
Point last = slope[0];
tmp = 1;
for(j = 1; j < m; j++) {
if(last.x == slope[j].x && last.y == slope[j].y) {
tmp++;
} else {
if(tmp > ans)
ans = tmp;
last = slope[j], tmp = 1;
}
}
if(tmp > ans)
ans = tmp;
}
printf("%d\n", ans+1);
if(t) puts("");
}
return 0;
}

台長: Morris
人氣(2,030) | 回應(0)| 推薦 (0)| 收藏 (0)| 轉寄
全站分類: 不分類 | 個人分類: UVA |
此分類下一篇:[UVA][Math] 920 - Sunny Mountains
此分類上一篇:[UVA][LIS&LDS] 10534 - Wavio Sequence

是 (若未登入"個人新聞台帳號"則看不到回覆唷!)
* 請輸入識別碼:
請輸入圖片中算式的結果(可能為0) 
(有*為必填)
TOP
詳全文