Problem Description
Coco is a clever boy, who is good at mathematics. However, he is puzzled by a difficult mathematics problem. The problem is: Given three integers N, K and M, N may adds (‘+’) M, subtract (‘-‘) M, multiples (‘*’) M or modulus (‘%’) M (The definition of ‘%’ is given below), and the result will be restored in N. Continue the process above, can you make a situation that “[(the initial value of N) + 1] % K” is equal to “(the current value of N) % K”? If you can, find the minimum steps and what you should do in each step. Please help poor Coco to solve this problem.
You should know that if a = b * q + r (q > 0 and 0 <= r < q), then we have a % q = r.
Input
There are multiple cases. Each case contains three integers N, K and M (-1000 <= N <= 1000, 1 < K <= 1000, 0 < M <= 1000) in a single line.
The input is terminated with three 0s. This test case is not to be processed.
Output
For each case, if there is no solution, just print 0. Otherwise, on the first line of the output print the minimum number of steps to make “[(the initial value of N) + 1] % K” is equal to “(the final value of N) % K”. The second line print the operations to do in each step, which consist of ‘+’, ‘-‘, ‘*’ and ‘%’. If there are more than one solution, print the minimum one. (Here we define ‘+’ < ‘-‘ < ‘*’ < ‘%’. And if A = a1a2...ak and B = b1b2...bk are both solutions, we say A < B, if and only if there exists a P such that for i = 1, ..., P-1, ai = bi, and for i = P, ai < bi)
Sample Input
2 2 2
-1 12 10
0 0 0
Sample Output
0
2
*+
Author
Wang Yijie
代码:
#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;
int n,k,m,ans,vis[1000006];
struct node
{
int res;
int cnt;
char a[1000];
}now,nex;
int mod(int a,int b)
{
return (a%b+b)%b;
}
void bfs()
{
queue<node>q;
memset(vis,0,sizeof(vis));
now.res=n;
now.cnt=0;
memset(now.a,0,sizeof(now.a));
q.push(now);
vis[mod(n,k)]=1;
while(!q.empty())
{
now=q.front();
q.pop();
if(mod(now.res,k)==mod(n+1,k))
{
printf("%d\n",now.cnt);
for(int i=0;i<now.cnt;i++)//直接改成printf("%s\n",now.a);会wa
printf("%c",now.a[i]);
printf("\n");
return;
}
strcpy(nex.a,now.a);
nex.cnt=now.cnt+1;
for(int i=1;i<=4;i++)
{
if(i==1)
{
nex.res=(now.res+m)%(k*m);
nex.a[now.cnt]='+';
}
else if(i==2)
{
nex.res=(now.res-m)%(k*m);
nex.a[now.cnt]='-';
}
else if(i==3)
{
nex.res=(now.res*m)%(k*m);
nex.a[now.cnt]='*';
}
else
{
nex.res=mod(now.res,m)%(k*m);
nex.a[now.cnt]='%';
}
if(!vis[mod(nex.res,k)])
{
q.push(nex);
vis[mod(nex.res,k)]=1;
}
}
}
printf("0\n");
}
int main()
{
while(~scanf("%d%d%d",&n,&k,&m),n||k||m)
bfs();
return 0;
}
本文介绍了一个涉及数学操作的复杂问题,目标是通过一系列加、减、乘、取模操作找到使初始值N加1后的结果与经过操作后的N对K取模相等的最短路径。文章提供了一段使用C++编写的程序代码,该程序采用广度优先搜索算法解决这个问题。
1691

被折叠的 条评论
为什么被折叠?



