USACO3.1.3--Humble Numbers

Humble Numbers

For a given set of K prime numbers S = {p1, p2, ..., pK}, consider the set of all numbers whose prime factors are a subset of S. This set contains, for example, p1, p1p2, p1p1, and p1p2p3 (among others). This is the set of `humble numbers' for the input set S. Note: The number 1 is explicitly declared not to be a humble number.

Your job is to find the Nth humble number for a given set S. Long integers (signed 32-bit) will be adequate for all solutions.

PROGRAM NAME: humble

INPUT FORMAT

Line 1: Two space separated integers: K and N, 1 <= K <=100 and 1 <= N <= 100,000.
Line 2: K space separated positive integers that comprise the set S.

SAMPLE INPUT (file humble.in)

4 19
2 3 5 7

OUTPUT FORMAT

The Nth humble number from set S printed alone on a line.

SAMPLE OUTPUT (file humble.out)

27
题解:自己写了个好暴力的程序,第四个点就超时了。。。木有想到怎么优化,只好看题解,照着题解翻译的,好失败%>_<%。直接贴官方题解好了。。
We compute the first n humble numbers in the "hum" array. For simplicity of implementation, we treat 1 as a humble number, and adjust accordingly.

Once we have the first k humble numbers and want to compute the k+1st, we do the following:

    for each prime p
        find the minimum humble number h
          such that h * p is bigger than the last humble number.

    take the smallest h * p found: that's the next humble number.
To speed up the search, we keep an index "pindex" of what h is for each prime, and start there rather than at the beginning of the list.
View Code
 1 /*
 2 ID:spcjv51
 3 PROG:humble
 4 LANG:C
 5 */
 6 #include<stdio.h>
 7 #include<string.h>
 8 long a[105];
 9 int f[105];
10 long num[100005];
11 int main(void)
12 {
13     freopen("humble.in","r",stdin);
14     freopen("humble.out","w",stdout);
15     long i,k,n,ans,min;
16     scanf("%ld%ld",&n,&k);
17     memset(f,0,sizeof(f));
18     num[0]=1;
19     for(i=1;i<=n;i++)
20         scanf("%ld",&a[i]);
21     ans=0;
22     while(ans<k)
23     {
24         min=0x7FFFFFFF;
25         for(i=1;i<=n;i++)
26         {
27             while(a[i]*num[f[i]]<=num[ans])
28             f[i]++;
29             if(a[i]*num[f[i]]<min) min=a[i]*num[f[i]];
30         }
31         ans++;
32         num[ans]=min;
33     }
34     printf("%ld\n",num[k]);
35     return 0;
36 }

 

posted on 2013-02-18 01:03  仗剑奔走天涯  阅读(167)  评论(0编辑  收藏  举报

导航