• 搜索:状态空间搜索


    倒水问题就是最典型的状态空间搜索了

    所谓的状态空间搜索我可以理解为,设定好起始条件,结束条件

    中间的过程是瞎搜

    也就是状态是一个隐式图

    有两个无刻度标志的水壶,分别可装 x 升和 y 升 ( x,y 为整数且均不大于 100 )的水。

    设另有一水 缸,可用来向水壶灌水或接从水壶中倒出的水, 两水壶间,水也可以相互倾倒。

    已知 x 升壶为空 壶, y 升壶为空壶。问如何通过倒水或灌水操作, 用最少步数能在x或y升的壶中量出 z ( z ≤ 100 )升的水 来

     1 #include<iostream>
     2 #include<cstring>
     3 using namespace std;
     4 const int INF=0x7f7f7f7f;
     5 const int maxn=105;
     6 int MIN(int x,int y)
     7 {
     8     return x<y?x:y;
     9 }
    10 int x,y,z;
    11 int ans=INF;
    12 int vis[maxn][maxn];
    13 void dfs(int x0,int y0,int dp)
    14 {
    15     if(dp>vis[x0][y0]) return;
    16     vis[x0][y0]=dp;
    17     if(x0==z||y0==z)
    18     ans=MIN(dp,ans);
    19     dfs(0,y0,dp+1);
    20     dfs(x0,0,dp+1);
    21     dfs(x,y0,dp+1);
    22     dfs(x0,y,dp+1);
    23     if(x0+y0<=y) dfs(0,x0+y0,dp+1);
    24     else dfs(x0+y0-y,y,dp+1);
    25     if(x0+y0<=x) dfs(x0+y0,0,dp+1);
    26     else dfs(x,x0+y0-x,dp+1);
    27 }
    28 int main()
    29 {
    30     cin>>x>>y>>z;
    31     memset(vis,INF,sizeof(vis));
    32     dfs(0,0,0);
    33     if(ans==INF) cout<<"impossible";
    34     else cout<<ans;
    35     return 0;
    36  } 

    我之前竟然一次就调出来了这个程序

    然后是刘汝佳版的倒水问题,它要求倒的水量最少

  • 相关阅读:
    Hamming Distance(随机算法)
    Difference Between Primes
    Pet(dfs)
    29. Divide Two Integers
    28. Implement strStr()
    25. Reverse Nodes in k-Group
    24. Swap Nodes in Pairs
    23. Merge k Sorted Lists
    22. Generate Parentheses
    19. Remove Nth Node From End of List
  • 原文地址:https://www.cnblogs.com/aininot260/p/9629793.html
Copyright © 2020-2023  润新知