P1008 ——1:2:3数字组合

来源:互联网 发布:广西广电网络网上缴费 编辑:程序博客网 时间:2024/05/02 00:32

将1,2,…,9共9个数分成三组,分别组成三个三位数,且使这三个三位数构成1:2:3的比例,试求出所有满足条件的三个三位数。

输入输出格式

输入格式:
木有输入

输出格式:
若干行,每行3个数字。按照每行第一个数字升序排列。


这题自己最初思路与刘汝佳的暴力枚举第一题有异曲同工之妙,都是九位不重复数字在搞事情,这是OJ的第一题,评论区大神解法太多了,我想用博客记录自己当时的想法,也是对一些更好思路解法的整理,C++STL中的next_permutation也是一个很好的暴力解决思想。

C语言暴力枚举

  • 用一个数组记录1-9出现次数,for循环if语句判断
#include<stdio.h>int judge(int a,int b,int c){    int flag[10]={0};    flag[0]=1;    while(a||b||c)    {        int aa=a%10;        a=a/10;    //分解后 数组计数        flag[aa]=1;        aa=b%10;        b=b/10;        flag[aa]=1;        aa=c%10;        c=c/10;        flag[aa]=1;    }    int sum=0;        for(int i=0;i<10;i++)        if((flag[i])&&(2*a==b&&3*a==c))   //条件判断        sum++;        if(sum==10)        return 1;    return 0;}int main(){    int i;    for(i=100;i<333;i++)    {        if(judge(i,2*i,3*i))        printf("%d %d %d\n",i,2*i,3*i);     } } 

C++STL(next_permutation)

next_permutation algorithm库
全排列:暴力穷举一个集合(数组)

http://blog.sina.com.cn/s/blog_9f7ea4390101101u.html
next_permutation 的用法


STL:#include <vector>#include <algorithm>#include <cstdio>using namespace std;int main(){    vector<int> v = vector<int>();    for( int i = 1 ; i <= 9 ; i ++ )        v.push_back(i);  //向数组添加元素    do{        int a = v[0]*100+v[1]*10+v[2];        int b = v[3]*100+v[4]*10+v[5];        int c = v[6]*100+v[7]*10+v[8];        if( a*2 == b && a*3 == c )            printf("%d %d %d\n",a , b , c );    }while( next_permutation( v.begin() , v.end() ) );----------Cint main(){   int v[9]={012345678} //向数组添加元素    do{        int a = v[0]*100+v[1]*10+v[2];        int b = v[3]*100+v[4]*10+v[5];        int c = v[6]*100+v[7]*10+v[8];        if( a*2 == b && a*3 == c )            printf("%d %d %d\n",a , b , c );    }while( next_permutation( v , v+8 ) );    return 0;}