zoukankan      html  css  js  c++  java
  • 三羊献瑞:dfs / next_permutation()

    三羊献瑞

    观察下面的加法算式:

           祥 瑞 生 辉
      +   三 羊 献 瑞
    -------------------
       三 羊 生 瑞 气

    (如果有对齐问题,可以参看【图1.jpg】)

    其中,相同的汉字代表相同的数字,不同的汉字代表不同的数字。

    请你填写“三羊献瑞”所代表的4位数字(答案唯一),不要填写任何多余内容。

     题目描述:答案1085

    dfs:

    #include <stdio.h>
    
    int a[] = {0,1,2,3,4,5,6,7,8,9};
    void test(int a[])
    {
    	if(a[0]==9&&a[4]==1){
     	int x=1000*a[0]+100*a[1]+10*a[2]+a[3];
     	int y=1000*a[4]+100*a[5]+10*a[6]+a[1];
     	int z=10000*a[4]+1000*a[5]+100*a[2]+10*a[1]+a[7];
        if(x+y==z) 
        	printf("%d + %d = %d
    ", x,y,z);	
    	}
    }
    
    void dfs(int a[], int k)
    {
        int i,t;
        if(k>=9){
            test(a);
            return;
        }
        
        for(i=k; i<10; i++){
            {t=a[k]; a[k]=a[i]; a[i]=t;}
            dfs(a,k+1);
            {t=a[k]; a[k]=a[i]; a[i]=t;} // 回溯
        }
    }
        
    int main()
    {
        dfs(a,0);    
        return 0;
    }
    

    next_permutation():

    #include<iostream>
    #include<algorithm>
    #include<cstdio>
    #include<math.h>
      
    using namespace std;
    int main()
    {
        int a[]={0,1,2,3,4,5,6,7,8,9};
        do{
            if(a[4]==1&&a[0]==9){
                int x=1000*a[0]+100*a[1]+10*a[2]+a[3];
                int y=1000*a[4]+100*a[5]+10*a[6]+a[1];
                int z=10000*a[4]+1000*a[5]+100*a[2]+10*a[1]+a[7];
                if(x+y==z){
                printf("%d+%d=%d
    ",x,y,z);
                break;
                }
            }
        }while(next_permutation(a,a+10));
         
        return 0;
    }
    
  • 相关阅读:
    回溯法之图的着色问题
    回溯法基本思想
    L2-006 树的遍历
    P1540 机器翻译
    P1067 多项式输出
    C++STL之map映照容器
    C++STL之multiset多重集合容器
    C++STL之set集合容器
    C++之string基本字符系列容器
    C++STL之vector向量容器
  • 原文地址:https://www.cnblogs.com/52dxer/p/10569599.html
Copyright © 2011-2022 走看看