PTA 1160 Forever (20 分)

1160 Forever (20 分)

"Forever number" is a positive integer A with K digits, satisfying the following constrains:

the sum of all the digits of A is m;
the sum of all the digits of A+1 is n; and
the greatest common divisor of m and n is a prime number which is greater than 2.
Now you are supposed to find these forever numbers.

Input Specification:

Each input file contains one test case. For each test case, the first line contains a positive integer N (≤5). Then N lines follow, each gives a pair of K (3<K<10) and m (1<m<90), of which the meanings are given in the problem description.

Output Specification:

For each pair of K and m, first print in a line Case X, where X is the case index (starts from 1). Then print n and A in the following line. The numbers must be separated by a space. If the solution is not unique, output in the ascending order of n. If still not unique, output in the ascending order of A. If there is no solution, output No Solution.

Sample Input:

2
6 45
7 80
Sample Output:
Case 1
10 189999
10 279999
10 369999
10 459999
10 549999
10 639999
10 729999
10 819999
10 909999
Case 2
No Solution

感悟

快PAT甲级考试了,开始准备一下PAT考试,PAT的题目真的是需要注重细节,这题没有去找什么数学规律,单纯的dfs加剪枝,感觉写的七七八八,交上只拿了一半分,卡了半小时细一琢磨发现没排序,然后拿了15分,又卡半小时发现没看见公约数要是素数,好好审题就不至于浪费一小时了...

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

typedef long long LL;
typedef pair<int,LL> PIL;

int k, m, flag;
PIL a[10010];

int gcd(int x, int y)
{
    return y == 0 ? x : gcd(y,x%y); 
}

int isprime(int x)
{
    if(x <= 1) return 0;
    for(int i = 2 ; i <= x/i ; i ++)
        if(x%i == 0) return 0;
    return 1;
}

void dfs(int cnt, int sum, LL x)
{
    if(cnt > k || sum > m || m > sum + 9*(k-cnt)) return;
    if(cnt == k && sum == m)
    {
        LL y = x + 1;
        int n = 0;
        while(y) n += (y%10),y /= 10;
        if(gcd(n,m) > 2 && isprime(gcd(n,m))) a[flag++] = {n, x};
        return;        
    }
    for(int i = 0 ;i <= 9 ; i ++)
        if(sum == 0 && i == 0)continue;
        else dfs(cnt + 1,sum + i,x*10 + i);
}

int main()
{
    int t;
    scanf("%d", &t);
    for(int i = 1 ; i <= t ; i ++ )
    {
        printf("Case %d\n", i);
        flag = 0;
        scanf("%d%d", &k, &m);
        dfs(0,0,0);
        if(!flag) printf("No Solution\n");
        else 
        {
            sort(a,a+flag);
            for(int i = 0 ; i < flag ; i ++)
                printf("%d %lld\n",a[i].first,a[i].second);
        }
    }

    return 0;
}
posted @ 2022-02-12 02:41  别问了我什么都不会  阅读(196)  评论(0编辑  收藏  举报