这道题用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;
}
求三连(~_~)~