方老师开橙卡
Time Limit: 3000/1000MS (Java/Others) Memory Limit: 65535/65535KB (Java/Others)
方老师最近迷上了炉石传说,但是他总是被土豪吊打。
方老师是万能的,他知道如何能开出橙卡:
方老师有一个幸运数字 n ,他开卡包的时候总会在屏幕上划出一个五芒星,假设方老师划出了 m 次五芒星,那么当 (m2)%(10x)=n(x=0,1,2,3⋯) ,对于某个 x 成立时,就会开出橙卡,请问方老师最少需要划出几次五芒星?如果方老师不可能开出橙卡,请告诉他。
Input
第一行有一个整数 T(T≤3000) ,代表测试数据的组数。
对于每组数据,每行有一个整数 N(0≤N≤109)
Output
对于每一组数据,如果
m
存在,输出
m
,否则输出None
Sample input and output
Sample Input | Sample Output |
---|---|
3 3 21 25 | None 11 5 |
Hint
(m2)%(10x)=n(x=0,1,2,3⋯) 只要有一个 x 满足就成立了
每次枚举一位数,从1位数字到9位数字,满足条件则加入队列。比如21,首先1*1 = 1 和 9*9 = 81 都满足个位与21的个位相同,加入队列,下次就考虑匹配第二位,然后第三位,。。
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <queue>
#include <math.h>
using namespace std;
int n;
struct node
{
long long m;
int x;
bool operator<(const node &t)const //依次从小的数开始,大的数肯定不行
{
return t.m<m;
}
};
long long bfs()
{
priority_queue<node>q;
node h,t;
h.m=0;
h.x=0;
q.push(h);
while (!q.empty())
{
t=q.top();
q.pop();
long long temp=(long long)pow(10,t.x);
if(t.m*t.m%temp==n)
{
return t.m;
}
for (int i=0; i<=9; i++)
{
h.m=t.m+i*temp; //t.m为已经从个位匹配的数字,i*temp为枚举下一个高位数字
h.x=t.x+1;
if(h.m*h.m%(temp*10)==n%(temp*10)) //测试这个高位是否符合条件
{
q.push(h);
}
}
}
return -1;
}
int main()
{
int t;
scanf("%d",&t);
while (t--)
{
scanf("%d",&n);
long long x=bfs();
if(x==-1)
{
printf("None\n");
}
else
{
printf("%lld\n",x);
}
}
return 0;
}