ZOJ 1005 Jugs

http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=5

递归模拟, 记录pair<a,b>是否被访问过。

View Code
const int MM = 111111;
#define  debug puts("wrong")
#define clr(a) memset(a,0,sizeof(a))
bool vis[1005][1005];
int op[MM];

int Ca, Cb, N;
bool ff;

void gao(int x) {
    if(x==1) puts("fill A");
    else if(x==2) puts("fill B");
    else if(x==3) puts("empty A");
    else if(x==4) puts("empty B");
    else if(x==5) puts("pour A B");
    else if(x==6) puts("pour B A");
    return ;
}
void print(int h) {
    for(int i=0;i<h;i++) gao(op[i]);
}
void dfs(int h,int ca,int cb,int opt) {
    int i,j,k,tmp;
    if(vis[ca][cb]||ff) return;
    vis[ca][cb]=true;
    if(ca==N || cb==N) {
        ff=true;
        print(h);
        puts("success");
        return;
    }
    if(opt!=3) op[h]=1,dfs(h+1,Ca,cb,1);
    if(opt!=4) op[h]=2,dfs(h+1,ca,Cb,2);
    if(opt!=1) op[h]=3,dfs(h+1,0,cb,3);
    if(opt!=2) op[h]=4,dfs(h+1,ca,0,4);
    if(opt!=6) op[h]=5,tmp=f_min(ca,Cb-cb),dfs(h+1,ca-tmp,cb+tmp,5);
    if(opt!=5) op[h]=6,tmp=f_min(cb,Ca-ca),dfs(h+1,ca+tmp,cb-tmp,6);
}
void solve() {
    int i,j,k;
    memset(vis,false,sizeof(vis));
    ff=false;
    dfs(0,0,0,-1);
}

int main() {
    while(scanf("%d%d%d",&Ca,&Cb,&N)!=EOF) solve();
    return 0;
}
原文地址:https://www.cnblogs.com/zhang1107/p/3026644.html