1196: Counting the Stars (2) (Topics in Structures)

1196: Counting the Stars (2) (Topics in Structures)

Title Description
One day, Xiao Ming was sitting in the yard counting the stars, and Gardon gave him a problem, asking him to count the maximum number of stars in the sky that are on the same straight line. There are too many stars in the sky, and Xiao Ming's eyes are immediately confused. Can you write a program to help him calculate it?
Input
First enter an integer N (N<=300), the next N pairs represent the position of a star (the coordinates of the stars are between -10000 and 10000, accurate to 1 decimal place). No two stars will ever be in the same place.
Output
An integer representing the maximum number of stars on a line.
Sample Input Copy
5
0 0
1 0
1 1
0 1
0.5 0.5
Sample Output Copy
3
Source/Classification

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define N 301
/*
1.两点确定一条直线
2.n>3时,先找出两个点确定一条直线,在剩余的n-2个点中找出在该直线上点的个数
    存放在数组中,数组大小(n-2)*(n-1)/2
3.判断第三个点是否与前两个点在同一条直线上
    (y3-y1)/(x3-x1)=(y3-y2)/(x3-x2)  没有将斜率不存在包含进去
    (y3-y1)*(x3-x2)==(y3-y2)*(x3-x1) 
*/

typedef struct point{
    
    
    double x;
    double y;
}point;



int main(){
    
    
    int n,h=0,a[45000]={
    
    0},max=0;
    point p[N];
    scanf("%d",&n);
    for(int i=0;i<n;i++){
    
    
        scanf("%lf %lf",&p[i].x,&p[i].y);
    }

    if(n==1) {
    
    
        printf("1\n");
        return 0;
    }
    if(n==2) {
    
    
        printf("2\n");
        return 0;
    }
    
    for(int i=0;i<n-2;i++){
    
    
        for(int j=i+1;j<n-1;j++){
    
    
            for(int k=j+1;k<n;k++){
    
    
                if((p[k].y-p[i].y)*(p[k].x-p[j].x)-(p[k].x-p[i].x)*(p[k].y-p[j].y)==0)
                    a[h]++;
            }
            h++;
        }
    }

    for(int i=0;i<h;i++){
    
    
        if(a[i]>max) max=a[i];
    }
    printf("%d\n",max+2);
    return 0;
}

Guess you like

Origin blog.csdn.net/weixin_44500344/article/details/108195607