P1927 防护伞

本文介绍了如何使用深度优先搜索(DFS)结合剪枝策略解决洛谷竞赛中的一个问题,计算两个点之间的伞形区域的最小面积,展示了在C++编程中处理几何问题的方法。

题目传送门:P1927 防护伞 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)

知识点:dfs + 剪枝 

// https://www.luogu.com.cn/problem/P1927
// dfs + 剪枝
#include<bits/stdc++.h>

using namespace std;

const double pai = 3.1415926535;
int n;
double ans = 1e9 + 7;
int x[1005], y[1005], st[1005];

double distance(int x1, int y1, int x2, int y2) {
    return pow(pow(x1 - x2, 2) + pow(y1 - y2, 2), 0.5);
}

// count1 伞的中心点   count2 第二个点   d count1到count2的距离
void dfs(int count1, int count2, double d) {
    if(d >= ans) return; // 剪枝 距离大于目前记录的最小距离的点不符合
    if(d) {
        // double xx = (x[count1] + x[count2]) / 2, yy = (y[count1] + y[count2]) / 2.0; 
        for(int i = 1; i <= n; i++) {
            if(!st[i]) {
                double dd = distance(x[count1], y[count1], x[i], y[i]);
                if(dd > d) 
                    return;
            }
        }
        ans <= d ? ans = ans : ans = d; // 更新ans
        return;
    }
    for(int i = 1; i <= n; i++) {
        if(!st[i]) {
            st[i] = 1;
            double dd = distance(x[count1], y[count1], x[i], y[i]);
            dfs(count1, i, dd);
            st[i] = 0;
        }
    }
}

int main() {
    cin >> n;
    // scanf("%d", &n);
    for(int i = 1; i <= n; i++) cin >> x[i] >> y[i];
    for(int i = 1; i <= n; i++) {
        st[i] = 1;
        dfs(i, 0, 0);
        st[i] = 0;
    }
    // cout << ans << '\n';
    double s;
    s = ans * ans * pai;
    // 不知道为什么直接输出s和用setprecision输出只有三个小数点  用printf就是正常的
    // cout << s << '\n';
    // cout << s << setprecision(4) << '\n';
    printf("%0.4lf\n", s);
    return  0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值