• 搜索


    搜索

    1.    深度优先搜索(dfs)

    a)    搜索的结构呈现树的形状

     

    #include<cstring>

    #include<cstdlib>

    #include<cstdio>

    #include<cmath>

    #include<iostream>

    using namespace std;

    int a[20],b[20],n,r;

    void dfs(int x)

    {

    if(x==r)

    {

      for(int i=1;i<=r;i++) printf("%d ",a[i]);

      printf(" ");

      return;

    }

     

    for(int i=1;i<=n;i++)

    {

      if(b[i]==1) continue;

      b[i]=1;

      a[x+1]=i;

      dfs(x+1);

      b[i]=0;

      a[x+1]=0;

    }

    }

    int main()

    {

    scanf("%d%d",&n,&r);

    dfs(0);

    return 0;

    }

    b)    用栈来存储.

    2.    广度优先搜索(bfs)

    a)    用队列存储。

    3.          #include<cstring>
    #include<cstdlib>
    #include<cstdio>
    #include<cmath>
    #include<iostream>
    using namespace std;
    int p[2000][3],c[5],n,r,tail,fr[2000];
    bool b[11][10][10];
    int q=0;
    void bfs()
    {

    c[0]=10;c[1]=7;c[2]=3;

    tail=1;
    p[1][0]=10;p[1][1]=p[1][2]=0;
    b[10][0][0]=1;

    for(int i=1;i<=tail;i++)
    {
    int a[3];
    for(int j=0;j<=2;j++) a[j]=p[i][j];

    for(int j=0;j<=2;j++)
    for(int k=0;k<=2;k++)
    {
    int t=min(a[j],c[k]-a[k]),tmp[3];
    tmp[0]=a[0];tmp[1]=a[1];tmp[2]=a[2];
    tmp[j]-=t;tmp[k]+=t;
    if(b[tmp[0]][tmp[1]][tmp[2]]==0)
    {
    b[tmp[0]][tmp[1]][tmp[2]]=1;
    tail++;
    fr[tail]=i;
    p[tail][0]=tmp[0];
    p[tail][1]=tmp[1];
    p[tail][2]=tmp[2];
    if(tmp[0]==5 && tmp[1]==5 && tmp[2]==0)
    {
    q=tail;
    return;
    }
    }
    }
    }
    }
    int main()
    {
    bfs();
    while(q)
    {
    printf("%d %d %d ",p[q][0],p[q][1],p[q][2]);
    q=fr[q];
    }
    }

  • 相关阅读:
    poj1014 Dividing (多重背包)
    HDOJ 1316 How Many Fibs?
    最大字串和
    WHY IE AGAIN?
    Codeforces Round #143 (Div. 2) (ABCD 思维场)
    自用组帧工具
    菜鸟学EJB(二)——在同一个SessionBean中使用@Remote和@Local
    shell 块注释
    检测到在集成的托管管道模式下不适用的 ASP.NET 设置的解决方法
    Windows Myeclipse 10 安装 Perl 插件
  • 原文地址:https://www.cnblogs.com/liumengliang/p/11193520.html
Copyright © 2020-2023  润新知