您的位置:首页 > Web前端

hdu - 1010 Tempter of the Bone (dfs+奇偶性剪枝) && hdu-1015 Safecracker(简单搜索)

2015-05-22 20:25 302 查看
http://acm.hdu.edu.cn/showproblem.php?pid=1010

这题就是问能不能在t时刻走到门口,不能用bfs的原因大概是可能不一定是最短路路径吧。

但是这题要过除了细心外,还需要强力的剪枝。

奇偶性剪枝:参考 http://www.cppblog.com/Geek/archive/2010/04/26/113615.html
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>
using namespace std;
char map[9][9];
int n,m,t,di,dj;
bool escape;
int dir[4][2]={{0,-1},{0,1},{1,0},{-1,0}};
void dfs(int si,int sj,int cnt)
{
if(cnt>10000) return;
if(escape) return;
if(si>n||sj>m||si<=0||sj<=0) return;
if(cnt==t&&si==di&&sj==dj)    escape=1;
if(escape) return;
if(cnt>=t) return;
int i,temp;
temp=(t-cnt)-abs(si-di)-abs(sj-dj);
if(temp<0||temp&1) return;
for(i=0;i<4;i++){
if(map[si+dir[i][0]][sj+dir[i][1]]!='X')
{
map[si+dir[i][0]][sj+dir[i][1]]='X';
dfs(si+dir[i][0],sj+dir[i][1],cnt+1);
map[si+dir[i][0]][sj+dir[i][1]]='.';
}
}
return;
}
int main()
{
int i,j,si,sj;
while(cin>>n>>m>>t)
{
if(n==0&&m==0&&t==0) break;
int wall=0;
for(i=1;i<=n;i++)
for(j=1;j<=m;j++)
{
cin>>map[i][j];
if(map[i][j]=='S') { si=i; sj=j; }
else if(map[i][j]=='D') { di=i; dj=j; }
else if(map[i][j]=='X') wall++;
}
if(n*m-wall<=t)
{
cout<<"NO"<<endl;
continue;
}
escape=0;
map[si][sj]='X';
dfs(si,sj,0);
if(escape) cout<<"YES"<<endl;
else cout<<"NO"<<endl;
}
return 0;
}

http://acm.hdu.edu.cn/showproblem.php?pid=1015
给定一个字符串和一个数n,然后再字符串中找出5个字符,满足题目中的等式并且字典序最大。

输入之后先把字符串从大到小排序,然后搜索即可。

#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;

bool cmp(char a,char b)
{
return a>b;
}

int k,j,flag,vis[15];
char s[15],ss[6],res[6];

bool judge(int v,int w,int x,int y,int z)
{
if(v-w*w+x*x*x-y*y*y*y+z*z*z*z*z==k)
return 1;
return 0;
}

void dfs(int x)
{
if(flag) return;
int i;
if(x==5)
{
if(judge(ss[0]-64,ss[1]-64,ss[2]-64,ss[3]-64,ss[4]-64)) {flag=1;strcpy(res,ss);}
return;
}
int l=strlen(s);
for(i=0;i<l;i++)
{
if(!vis[i])
{
vis[i]=1;
ss[x]=s[i];
dfs(x+1);
vis[i]=0;
}
}
}

int main()
{
int i;
//freopen("a.txt","r",stdin);
while(scanf("%d %s",&k,s)!=EOF&&k!=0&&strcmp(s,"END")!=0)
{
flag=0;
sort(s,s+strlen(s),cmp);
memset(vis,0,sizeof(vis));
dfs(0);
if(flag)
{
printf("%s\n",res);
}
else printf("no solution\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: