pku 3278

http://poj.org/problem?id=3278

可能写DFS写的比较习惯吧,每次只要遇到搜索提就会用DFS写。结果DFS版本各种剪枝后还是TLE郁闷。。求用dfs过的大牛代码。。

后来用了bfs中间还是出了点小问题,考虑不认真造成的。

BFS

View Code
#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
using namespace std;
int ans,s,e;
bool visit[100007];
struct node
{
int pos;
int ct;
};
queue<node>q;

void bfs()
{
while (!q.empty()) q.pop();
node tmp,po;
tmp.ct = 0;
tmp.pos = s;
q.push(tmp);
visit[tmp.pos] = true;
while (!q.empty())
{
tmp = q.front();
q.pop();
if (tmp.pos == e)
{
ans = tmp.ct;
break;
}
for (int i = 0; i < 3; ++i)
{
if (i == 0) po.pos = tmp.pos + 1;
else if (i == 1) po.pos = tmp.pos - 1;
else po.pos = tmp.pos*2;
po.ct = tmp.ct + 1;
if (po.pos >= 0 && po.pos <= 100000 && !visit[po.pos])//才开始没考虑pos的取值导致了re了一次,
//后来考虑到了可是把visit[]放在了最前边,对pos的限制在visit里面还是没起作用,最后移到后面就欧了
{
visit[po.pos] = true;
q.push(po);
}
}

}
}
int main()
{
while (~scanf("%d%d",&s,&e))
{
memset(visit,false,sizeof(visit));
if (s == e)
{
printf("0\n");
continue;
}
if (s > e)
{
printf("%d\n",s - e);
continue;
}
if (s*2 == e)
{
printf("1\n");
continue;
}
bfs();
printf("%d\n",ans);
}
}

DFS tle中。。。

View Code
#include <iostream>
#include <cstring>
#include <cstdio>
#define maxn 107
using namespace std;
int s,e;
int ans;
void dfs(int st,int count)
{
if (count > ans) return ;//剪枝
if (st == e)
{
if (ans > count)
ans = count;
return ;
}
if (st < 0 || st > 100000) return ;
for (int i = 0; i < 3; ++i)
{
if (i == 0)
{
dfs(st + 1,count + 1);
}
else if (i == 1)
{
dfs(st - 1,count + 1);
}
else
{
dfs(st*2,count + 1);
}
}
}
int main()
{
while (~scanf("%d%d",&s,&e))
{
ans = 999999999;
if (s == e)
{
printf("0\n");
continue;
}
if (s > e)
{
printf("%d\n",s - e);
continue;
}
if (s*2 == e)
{
printf("1\n");
continue;
}
dfs(s,0);
printf("%d\n",ans);
}
return 0;
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值