• [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;
    }
    
  • 相关阅读:
    《最优化导论》-8梯度方法
    《最优化导论》-7一维搜索方法
    《最优化导论》-6集合约束和无约束优化问题基础
    ubuntu set up 3
    ubuntu set up 2
    ubuntu set up 1
    Xavier and Kaiming Initialization
    Network Initialization: Fan-in and Fan-out
    The Softmax function and its derivative
    GNU Screen使用
  • 原文地址:https://www.cnblogs.com/mrha/p/8024290.html
Copyright © 2020-2023  润新知