HDU 1104 Remainder

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

*+

广搜,不过要注意的是%的问题,为了不重复走同一个点以k*m为总大小即可。

所有%k和%m的可能都在%km里了。

#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<map>
#include<queue>
#include<stack>
#include<vector>
#include<cstdlib>
#include<functional>
#include<string>
using namespace std;
const int maxn = 1000005;
const int mod(int x, int y){return (x % y + y) % y;}
int n, k, m, km, f[maxn];
char C[5] = { "+-*%" };

struct abc
{
	int x, y;
	string s;
	abc(){}
	abc(int x, int y, string s) :x(x), y(y), s(s){}
};

int get(int x, int y)
{
	if (y == 0) return mod(x + m, km);
	if (y == 1) return mod(x - m, km);
	if (y == 2) return mod(x * m, km);
	if (y == 3) return mod(x % m, km);
}

void bfs(int z)
{
	memset(f, 0, sizeof(f));
	queue<abc> p;
	km = k*m;
	n = mod(n, km);	f[n] = 1;
	p.push(abc(n, 0, ""));
	while (!p.empty())
	{
		abc q = p.front();	p.pop();
		if (mod(q.x, k) == z) { cout << q.y << endl << q.s << endl; return; }
		for (int i = 0; i < 4; i++)
		{
			int x = get(q.x, i);
			if (!f[x]) f[x] = 1; else continue;
			p.push(abc(x, q.y + 1, q.s + C[i]));
		}
	}
	printf("0\n");
}

int main()
{
	while (scanf("%d%d%d", &n, &k, &m), n + k + m) bfs(mod(n + 1, k));
}


你可能感兴趣的:(HDU,广搜)