洛谷 P1433 吃奶酪

这道题用DFS怎么做???

是很多蒟蒻的疑问。。。

没事,今天就由我这个

超级无敌宇宙第一大蒟蒻解答


正文开始

首先,你要先打出一个正常人都能打出的DFS(如下)

#include <bits/stdc++.h>
using namespace std;

typedef double db;
int n;
db ans = DBL_MAX;
struct node {
    db x;
    db y;
    bool vis;
} a[16];

inline int read() {
    cin >> n;
    for(int i = 1; i <= n; i ++)
        cin >> a[i].x >> a[i].y;
}

db dx(db x1, db y1, db x2, db y2) {
    return sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
}

void dfs(int t, db cnt, int l) {
    if(t > n) {
        ans = cnt;
        return;
    }
    for(int i = 1; i <= n; i ++)
        if(!a[i].vis) {
            a[i].vis = 1;
            if(cnt + dx(a[l].x, a[l].y, a[i].x, a[i].y) <= ans)
                dfs(t + 1, cnt + dx(a[l].x, a[l].y, a[i].x, a[i].y), i, c + 1);
            a[i].vis = 0;
        }
}

int main() {
    ios :: sync_with_stdio(0);
    read();
    dfs(1, 0, 0);
    printf("%.2lf", ans);
    return 0; 
}

提交上去,会发现

只拿了90分,还有一个TLE

开O2优化,还是

TLE

别急,接下来(拉线)


有一个方法,叫卡时

不要在竞赛使用,除非你有把握

假设一个最大运行次数(保证不TLE)

然后如果达到了这个次数,输出答案(目前最标准)

if(运行次数 >= 上限) {
    cout << 答案;
    return;
}

PS: 我是抄数据的……


AC代码

#include <bits/stdc++.h>
using namespace std;

typedef double db;
int n;
db ans = DBL_MAX;
struct node {
    db x;
    db y;
    bool vis;
} a[16];

inline int read() {
    cin >> n;
    for(int i = 1; i <= n; i ++)
        cin >> a[i].x >> a[i].y;
}

db dx(db x1, db y1, db x2, db y2) {
    return sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
}

void dfs(int t, db cnt, int l, int c) {
    if(c > 15) {
        cout << 21.73;
        exit(0);
    }
    if(t > n) {
        ans = cnt;
        return;
    }
    for(int i = 1; i <= n; i ++)
        if(!a[i].vis) {
            a[i].vis = 1;
            if(cnt + dx(a[l].x, a[l].y, a[i].x, a[i].y) <= ans)
                dfs(t + 1, cnt + dx(a[l].x, a[l].y, a[i].x, a[i].y), i, c + 1);
            a[i].vis = 0;
        }
}

int main() {
    ios :: sync_with_stdio(0);
    read();
    dfs(1, 0, 0, 1);
    printf("%.2lf", ans);
    return 0; 
}

求三连(~_~)~

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值