zoukankan      html  css  js  c++  java
  • [zoj] 1937 [poj] 2248 Addition Chains || ID-DFS

    原题

    给出数n,求出1......n 一串数,其中每个数字分解的两个加数都在这个序列中(除了1,两个加数可以相同),要求这个序列最短。


    ++m,dfs得到即可。并且事实上不需要提前打好表,直接输出就可以。

    #include<cstdio>
    using namespace std;
    int dep=0,n;
    int a[102];
    bool dfs(int step)
    {
      if(step>dep) return a[dep]==n;
      for(int i=0;i<step;i++)
        {
          if(a[step-1]+a[i]>n) break;
          a[step]=a[step-1]+a[i];
          if(dfs(step+1)) return 1;
        }
      return 0;
    }
    int main()
    {
      a[0]=1;
      while(~scanf("%d",&n)&&n)
        {
          dep=0;
          while(!dfs(1)) ++dep;
          for(int i=0;i<=dep;i++) printf("%d%c",a[i]," 
    "[i==dep]);
        }
      return 0;
    }
    

    提前打表:

    #include<cstdio>
    using namespace std;
    int n,s[110]={0,1,2},cnt=3,l[110]={0,1,2},ans[110][20]={{0},{0,1},{0,1,2}};
    
    void dfs(int x)
    {
        if (x>cnt) return ;
        for (int i=1;i<x;i++)
    	for (int j=i;j<x;j++)
    	{
    	    s[x]=s[i]+s[j];
    	    if (s[x]>100 || s[x]<=s[x-1]) continue;
    	    if (!l[s[x]] || l[s[x]]>x)
    	    {
    		l[s[x]]=x;
    		for (int l=1;l<=x;l++)
    		    ans[s[x]][l]=s[l];
    	    }
    	    dfs(x+1);
    	}
    }
    
    int main()
    {
        while (cnt<=10) dfs(3),++cnt;//因为a[1]和a[2]是固定的
        while(~scanf("%d",&n) && n)
        {
    	for (int i=1;i<=l[n];i++)
    	    printf("%d%c",ans[n][i]," 
    "[i==l[n]]);
        }
        return 0;
    }
    
  • 相关阅读:
    ★★★
    ★★
    小狼程序员:工作遐想
    广联达BB了
    计算机网络简单理解
    做个合格的(优秀的)测试开发人员
    开发、测试、测试开发
    8.21
    C++ 选择题总结(回调函数 || 类方法(实例方法)|| )
    深拷贝实现笔记
  • 原文地址:https://www.cnblogs.com/mrha/p/8024290.html
Copyright © 2011-2022 走看看