HDU 1104 Remainder
题意:
给你N,M,K3个数,求N和M通过{ + , - , * , %}这些运算,最少能几步到达(N(最初的) + 1) % K 和 N(最终的) % K 相等。并输出每次的操作符。
比如+-* 就是 ((N + M) - M) * M,每次都用计算过的值进行计算。
思路:
由于最终结果都和K取余数,所以范围就是【-1000,1000】,直接进行广搜就可以,把搜过的数都记录下来,并用string记录路径。
其中有个点就是+,-,* 都可以每次运算后取模是没有问题的,但是注意%M之后不能%K,因为不符合以上规律。
比如N = 2, K = 3, M = 8.
((n * m) % k % m) % k = 1
(n * m % m) % k = 0。
所以每次需要和K * M 进行%运算。
还有就是% 的话,根据题意负数%会变成整数,所以需要(N % K + K)% K。
Code:
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cctype>
#include<cmath>
#include<algorithm>
#include<iostream>
#include<string>
#include<vector>
#include<bitset>
#include<queue>
#include<stack>
#include<list>
#include<map>
#include<set>
#define TEST
#define LL long long
#define Mt(f, x) memset(f, x, sizeof(f));
#define rep(i, s, e) for(int i = (s); i <= (e); ++i)
#ifdef TEST
#define See(a) cout << #a << " = " << a << endl;
#define See2(a, b) cout << #a << " = " << a << ' ' << #b << " = " << b << endl;
#define debug(a, s, e) rep(_i, s, e) {cout << a[_i] << ' ';} cout << endl;
#define debug2(a, s, e, ss, ee) rep(i_, s, e) {debug(a[i_], ss, ee)}
#else
#define See(a)
#define See2(a, b)
#define debug(a, s, e)
#define debug2(a, s, e, ss, ee)
#endif // TEST
const int MAX = 2e9;
const int MIN = -2e9;
const double eps = 1e-8;
const double PI = acos(-1.0);
using namespace std;
const int NUM = 2e3 + 5;
int N, K, M;
int mod;
char op[] = {'+', '-', '*', '%'};
struct Node
{
int n;
string s;
int tep;
Node() : s(""), tep(0) {}
Node(int n, int tep, string s) : n(n), tep(tep), s(s) {}
}st, to;
int suan(int n, char c)
{
if(c == '+')
return n + M;
if(c == '-')
return n - M;
if(c == '*')
return n * M;
if(c == '%')
return (n % M + M) % M;
}
void bfs()
{
st = Node(N, 0, "");
map<int, int> Map;
Map[(N % K + K) % K] = 1;
queue<Node> Q;
Q.push(st);
while(!Q.empty())
{
st = Q.front(); Q.pop();
if((st.n % K + K) % K == mod)
{
printf("%d\n", st.tep);
cout << st.s << endl;
return ;
}
for(int i = 0; i < 4; ++i)
{
int t = suan(st.n, op[i]) % (K * M);
if(!Map[t])
{
Map[t] = true;
to = Node(t, st.tep + 1, st.s + op[i]);
Q.push(to);
}
}
}
printf("0\n");
}
int main()
{
while(~scanf("%d%d%d", &N, &K, &M))
{
if(N == 0 && K == 0 && M == 0)
{
return 0;
}
mod = ((N + 1) % K + K) % K;
bfs();
}
return 0;
}