算法提高 连接乘积


算法提高 连接乘积  
时间限制:1.0s   内存限制:256.0MB
    
问题描述
  192这个数很厉害,用它分别乘以1、2、3,会得到:
  192 x 1 = 192
  192 x 2 = 384
  192 x 3 = 576
  把这三个乘积连起来,得到192384576,正好是一个1~9的全排列
  我们把上面的运算定义为连接乘积:
  m x (1 ... n) = k(其中m > 0 且 n > 1,对于上例,m = 192、n = 3、k = 192384576)
  即k是把m分别乘以1到n的乘积连接起来得到的,则称k为m和n的连接乘积。
  按字典序输出所有不同的连接乘积k,满足k是1~9的全排列
输出格式
  每个k占一行
样例输出
显然,结果中应包含一行:
192384576

思路分析:推测范围大小,暴力解决,详情看代码。

#include <cstdio>
#include <string>
#include <algorithm>
#include <vector>
#include <iostream>

using namespace std;

vector<string> ans;

string s[] = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };

string intToString( int n ) {
    string ans;
    while( n ) {
        ans = ans + s[n % 10];
        n = n / 10;
    }
    reverse( ans.begin(), ans.end() );

    return ans;
}

bool check( string str ) {
    int visit[10] = { 0 };
    for( int i = 0; i < str.size(); i++ ) {
        visit[str[i] - '0']++;
    }
    if( visit[0] > 0 ) return false;
    for( int i = 1; i < 10; i++ ) {
        if( visit[i] != 1 ) {
            //printf( "%d Error\n", i );
            return false;
        }
    }
    return true;
}

int main() {

    // i < 9999也行,999不行
    for( int i = 1; i < 99999; i++ ) {
        string str;
        for( int j = 1; j < 10; j++ ) {
            str = str + intToString( i * j );
            if( check( str ) ) {
                ans.push_back( str );
                //cout << str << endl;
                break;
            }
        }
    }

    sort( ans.begin(), ans.end() );
    for( int i = 0; i < ans.size(); i++ ) {
        cout << ans[i] << endl;
    }
    return 0;
}



  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值