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
思路:
1.dfs爆搜,从左到右枚举A的每一位数,但是要注意剪枝,比如前x位和为sum时,后面k-x位都取9时是否能依然小于m-sum,如果是的话可以剪掉。
2.另一种方法是通过观察我们发现最后一位必为9,因为如果非9的话A和A+1必定是互质的,如果末尾有连续x个9,那么位数的和会减掉8+9*(x-1), 然后枚举位末尾连续9的位数加上适当判断剪枝即可。
坑点:
答案要按序输出,所以把答案先存到结构体里,然后优先对n升序排序,再对A升序排序。
#include<bits/stdc++.h>
using namespace std;
#define ll long long
int k, m;
struct node
{
int n;
ll A;
};
node nd[100005];
int cnt;
bool cmp(node a, node b)
{
if (a.n == b.n)
{
return a.A < b.A;
}
return a.n < b.n;
}
int prime(int x)
{
for (int i = 2; i * i <= x; ++i)
{
if (x % i == 0)
{
return 0;
}
}
return 1;
}
int gcd(int a, int b)
{
if (b == 0)return a;
else return gcd(b, a % b);
}
int calc(ll x)
{
int ans = 0;
while (x > 0)
{
ans += x % 10;
x /= 10;
}
return ans;
}
int f = 0;
void dfs(int x,int sum,ll now)
{
if (x == k + 1&&sum==m)
{
int y = calc(now + 1);
if (gcd(y, sum) > 2 && prime(gcd(y, sum)))
{
f = 1;
nd[++cnt].n = y;
nd[cnt].A=now;
}
return;
}
else if (x == k + 1 && sum != m)
{
return;
}
if ((k - x+1) * 9 < m - sum||sum>m)return;
if (x != 1)dfs(x + 1, sum, now * 10);
for (int i = 1; i <= 9; ++i)
{
dfs(x+1, sum + i, now * 10 + i);
}
}
int main()
{
int n; cin >> n;
for(int i=1;i<=n;++i)
{
cout << "Case " << i << endl;
f = 0;
cnt = 0;
cin >> k >> m;
dfs(1, 0, 0);
if (f == 0)
{
cout << "No Solution" << endl;
}
else
{
sort(nd + 1, nd + cnt + 1,cmp);
for (int j = 1; j <= cnt; ++j)
{
printf("%d %lld\n", nd[j].n, nd[j].A);
}
}
}
}