c++ - 一道编程题,算法提高 Problem S4: Interesting Numbers 加强版
PHP中文网
PHP中文网 2017-04-17 13:44:53
[C++讨论组]

Problem Description
  We call a number interesting, if and only if:
  1. Its digits consists of only 0, 1, 2 and 3, and all these digits occurred at least once.
  2. Inside this number, all 0s occur before any 1s, and all 2s occur before any 3s.
  Therefore, the smallest interesting number according to our definition is 2013. There are two more interseting number of 4 digits: 2031 and 2301.

Your task is to calculate the number of interesting numbers of exactly n digits. As the answer might be very large, you only need to output the answer modulo 1000000007.

Input Format

The input has one line consisting of one positive integer n (4 ≤ n ≤ 10^15).

Output Format

The output has just one line, containing the number of interesting numbers of exactly n digits, modulo 1000000007.

Input Sample

4

Output Sample

3

我用了两个dfs,当4的时候是对的,但是10的时候数据差据很大,我把数据打出来感觉没错,不知道这道题怎么做了?

#include<iostream>
#include<cstdio>
#define N 1000000007

using namespace std;

int data[4]={1,1,1,1};
int dfs2(int n,int* num,int u);
int count = 0;
int temp[100]={0};

int dfs1(int n,int u)
{
    if (n>u) {
        return 0;
    }
    
    if (n==u) {
        dfs2(0,data,u+4);
    }
    else {
        for(int i=0;i<4;i++) {
            data[i]++;
            dfs1(n+1,u);
            data[i]--;
        }
    }
}

int dfs2(int n,int* num,int u)
{
    if (n>u) {
        return 0;
    }
     
    if (n==u) {
        count=count%N;
        count++;
        /*    for(int i=0;i<n;i++)
        cout<<temp[i]<<" ";
        cout<<endl;*/ 
    } 
    else {
        for (int i=0;i<4;i++) {
            if (i==1 && num[0]>0) {
                continue;
            }
            
            if (i==3 && num[2]>0) {
                continue;
            }
            
            if (i==0 && n==0)
                continue;
                
            if (num[i]>0) {
                num[i]--;
                temp[n]=i;
                dfs2(n+1,num,u);
                num[i]++;
            }
        }
    }
}

int main()
{
    int n;
    cin >> n;
    dfs1(0,n-4);
    cout << count;
} 
PHP中文网
PHP中文网

认证0级讲师

全部回复(0)
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号