BZOJ 1610 Usaco Line

本文介绍了解决一道关于几何问题的编程题目的两种方法:一种使用Set数据结构,另一种采用排序方法。通过对比这两种方法,展示了如何有效避免精度问题,并给出了具体的代码实现。

一道很水的题目,一开始用Set做。莫名其妙WA了,后来想了想。
精度问题很关键!!!

Set AC写法

#include <cstdio>
#include <algorithm>
#include <set>
 
using namespace std;
 
 
int n,tot;
double x[233],y[233];
double k,eps=1e-10;
 
struct CMP{
    inline bool operator()(const double x,const double y)const{
        return x>eps+y;
    }
};
 
set<double,CMP>s;
 
int main(){
    scanf("%d",&n);
    for(int i=1;i<=n;i++){
        scanf("%lf%lf",&x[i],&y[i]);
    }
    for(int i=1;i<n;i++){
        for(int j=i+1;j<=n;j++){
            double fy = y[i] - y[j];
            double fx = x[i] - x[j];
            if(fx==0) s.insert(99999999);
            else s.insert(fy/fx);
        }
    }
    printf("%d\n",s.size());
    return 0;
}
Set

 

Sort AC写法

#include <cstdio>
#include <algorithm>
#include <cmath>
using namespace std;
 
 
int n,tot=1,pos;
int x[202],y[202];
double k[200005];
 
int main(){
    scanf("%d",&n);
    for(int i=1;i<=n;i++){
        scanf("%d%d",&x[i],&y[i]);
    }
    for(int i=1;i<=n;i++){
        for(int j=i+1;j<=n;j++){
            double fy = y[i] - y[j];
            double fx = x[i] - x[j];
            if(fy==0) k[++pos] = 0;
            else if(fx==0) k[++pos]=1000000;
            else k[++pos] = fy/fx;
        }
    }
    std::sort(k+1,k+pos+1);
    for(int i=2;i<=pos;i++){
        if( fabs(k[i]-k[i-1]) > 1e-10) tot++;
    }
    printf("%d\n",tot);
    return 0;
}
Sort

 

转载于:https://www.cnblogs.com/OIerLYF/p/7496120.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值