HDU 3199 Hamming Problem 醜數

Time Limit:1000MS Memory Limit:32768KB 64bit IO Format:%I64d & %I64u
Submit

Status
Description
For each three prime numbers p1, p2 and p3, let’s define Hamming sequence Hi(p1, p2, p3), i=1, … as containing in increasing order all the natural numbers whose only prime divisors are p1, p2 or p3.

For example, H(2, 3, 5) = 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24, 25, 27, …

So H5(2, 3, 5)=6.

Input
In the single line of input file there are space-separated integers p1 p2 p3 i.

Output
The output file must contain the single integer - Hi(p1, p2, p3). All numbers in input and output are less than 10^18.

Sample Input
7 13 19 100

Sample Output
26590291

題意分析

  • 給定三個素數p1,p2,p3;
  • H(p1,p2,p3)爲連續遞增的自然數,且其質因數的集合只能屬於{p1,p2,p3};
  • 求第n個在H()這個序列裏的數

    解題思路

  • 考慮的範圍,一定不是每個數嘗試分解質因數

  • 數學定理:任何一個合數都可以寫成幾個質數相乘的形式。其中每個質數都是這個合數的因數,叫做這個合數的分解質因數。分解質因數只針對合數。(自行百度);
  • 分類:1+質數+合數=全部自然數:不包括1;質因數分解只有1和其本身(也就是說H序列裏的質數只有p1,p2,p3);剩下的都是合數(都能分解成幾個質數)反過來想就是由(p1,p2,p3)中任意n個組合相乘(這裏描述不太嚴謹,看代碼)

    代碼

#include<iostream>
#include<cstdio>
#include<set>
#include<queue>
#include<vector>
using namespace std;
long long p[3];
int n;
int main(){

    while(  cin>>p[0]>>p[1]>>p[2]>>n){

        priority_queue<long long,vector<long long>,greater<long long> > Q;
        set<long long> S;
        Q.push(1);
        S.insert(1);
        for(int i=1;;i++){
            long long x=Q.top();Q.pop();
            if(i==n+1){
                cout<<x<<endl;
                break;
            }
            for(int j=0;j<3;j++){
                long long t=x*p[j];
                if(!S.count(t)){
                    Q.push(t);
                    S.insert(t);
                }
            }
        }
    }

    return 0;
}

DFS實現

ans=1;
dfs(ans)
for i=0 to 2 dfs(ans*pi);
保存ans序列並排序去重,當ans大於18位時退出
(當然,並沒有實現,不確定對錯)
##三

號稱dp的解法

hdu1058

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章