Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 12616 | Accepted: 7145 |
Description
1033The cost of this solution is 6 pounds. Note that the digit 1 which got pasted over in step 2 can not be reused in the last step – a new 1 must be purchased.
1733
3733
3739
3779
8779
8179
Input
Output
Sample Input
3 1033 8179 1373 8017 1033 1033
Sample Output
6 7 0
题目大意:
这道题目是说,给你一个l和r,并且l和r都是素数,问你如何通过最小的步数使得l变成r,并且每次变化只能变一个位置的数字,且每次变化完后都是素数
解题思路:
直接bfs就好,每次将个位,十位,百位,千位的变化后的数字压入队列,然后判断是不是使我们所要求的那个数字,然后记录步数就好了。
代码:
# include
# include
# include
# include
using namespace std;
# define MAX 10000
int prime[MAX];
int book[MAX];
int path[MAX];
int l,r;
void init()
{
for ( int i = 2;i < 10000;i++ )
{
prime[i] = 1;
}
for ( int i = 2;i < 100;i++ )
{
if ( prime[i] )
{
for ( int j = 1;i*j < 10000;j++ )
{
prime[i*j] = 0;
}
}
}
}
void bfs()
{
queueq;
q.push(l);
book[l] = 1;
while ( !q.empty() )
{
int temp = q.front();
q.pop();
if ( temp == r )
break;
for ( int t = 1;t <= 1000;t*=10 )
{
int d = temp;
d/=t;
d%=10;
int rec = temp-d*t;
for ( int j = 0;j <= 9;j++ )
{
if ( t == 1000&&j==0 )
{
continue;
}
if ( j!=d )
{
int cur = j*t+rec;
if ( prime[cur]==1&&book[cur]==0 )
{
q.push(cur);
path[cur] = path[temp]+1;
book[cur] = 1;
}
}
}
}
}
}
int main(void)
{
int t;cin>>t;
while ( t-- )
{
memset(book,0,sizeof(book));
memset(path,0,sizeof(path));
cin>>l>>r;
init();
bfs();
cout<