HDU1495(bfs)
非常可乐
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 10349 Accepted Submission(s):
4143
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<queue>
#include<algorithm>
using namespace std;
const int MAX=105;
int s,n,m;
struct node{
int s,n,m,t;
};
int vis[MAX][MAX][MAX];
int bfs(){
node now,next;
queue<node>q;
while(!q.empty())
q.pop();
now.s=s;now.n=now.m=now.t=0;
memset(vis,0,sizeof(vis));
vis[s][0][0]=1;
q.push(now);
while(!q.empty()){
now=q.front(),q.pop();
if((now.n==now.m&&now.s==0)||(now.n==now.s&&now.m==0)||(now.s==now.m&&now.n==0))
return now.t;
int tmp;
if( now.s!=0 ){
if( now.n!=n ){
tmp=min( now.s,n-now.n );
next=now;
next.t=now.t+1;
next.s-=tmp;
next.n+=tmp;
if( vis[next.s][next.n][next.m]==0/*vis[ next ]==0*/ ){
vis[next.s][next.n][next.m]=1;//vis[ next ]=1;
q.push(next);
}
}
if( now.m!=m ){
tmp=min( now.s,m-now.m );
next=now;
next.t=now.t+1;
next.s-=tmp;
next.m+=tmp;
if( vis[next.s][next.n][next.m]==0/*vis[ next ]==0*/ ){
vis[next.s][next.n][next.m]=1;//vis[ next ]=1;
q.push( next );
}
}
}// 1 to (2 or 3)
if(now.n!=0){
tmp=now.n;
next=now;
next.t=now.t+1;
next.s+=tmp;
next.n=0;
if( vis[next.s][next.n][next.m]==0/*vis[ next ]==0*/ ){
vis[next.s][next.n][next.m]=1;//vis[ next ]=1;
q.push( next );
}
if( now.m!=m ){
tmp=min(m-now.m,now.n);
next=now;
next.t=now.t+1;
next.m+=tmp;
next.n-=tmp;
if(vis[next.s][next.n][next.m]==0/*vis[ next ]==0*/){
vis[next.s][next.n][next.m]=1;//vis[ next ]=1;
q.push( next );
}
}
}//2 to( 1 or 3 )
if( now.m!=0 ){
tmp=now.m;
next=now;
next.t=now.t+1;
next.m=0;
next.s+=tmp;
if( vis[next.s][next.n][next.m]==0/*vis[ next ]==0*/ ){
vis[next.s][next.n][next.m]=1;//vis[ next ]=1;
q.push( next );
}
if( now.n!=n ){
tmp=min( n-now.n,now.m );
next=now;
next.t=now.t+1;
next.n+=tmp;
next.m-=tmp;
if( vis[next.s][next.n][next.m]==0/*vis[ next ]==0*/ ){
vis[next.s][next.n][next.m]=1;//vis[ next ]=1;
q.push( next );
}
}
}
}
return -1;
}
int main(){
while( scanf("%d%d%d",&s,&n,&m),s+n+m )
{
if( s%2==1 ){
printf("NO\n");
continue;
}
if( n==m ){
printf("1\n");
continue;
}
int ans=bfs();
if( ans!=-1 )
printf("%d\n",ans);
else
printf("NO\n");
}
return 0;
}
这是一个经典的广搜题,开始我是用java编写的,但是总是写不对,后来询问了一下老师,老师说要拷贝now里面的数据再去倒;这个地方有几个小细节大家应该要注意。这里基本上采用了暴力列举,把六种情况列举了出来。先是从1倒到或2,把他们倒满,再是从2倒到3或者是1把2的中的水倒完。3倒到1或者2,把3中的水倒完;