Prime Path POJ - 3126

大佬的题解

根据大佬思路写的

#include<cstdio>
#include<iostream>
#include<cstring>
#include<cmath>
#include<queue>
#include<string>
using namespace std;
string a, b;
int p[11111];
int v[11111];
int cnt;
int vis[11111];
int ans;

struct sz
{
	string s;
	int step;
};
int s_int(string s)
{
	int a = 0;
	for(int i = 0; i < s.length(); i++)
	{
		a = a*10 + (s[i] - '0');
	}
	return a;
}
queue <sz> q;
void bfs()
{
	while(!q.empty())
	{
		sz now;
		now = q.front();
		q.pop();
		if(now.s == b){
			//cout << now.s << "\n";
			cout << now.step << "\n";
			return;
		}
		for(int i = 0; i < 4; i++)
		{
			for(int j = 0; j < 10; j++)
			{
				if(i == 0 && j == 0) continue;
				sz next = now;
				next.step++;
				next.s[i] = j + '0';
				int cmp = s_int(next.s);
				if(!vis[cmp] && !v[cmp])
				{
					vis[cmp]=1;
					q.push(next);	
					//cout << next.s << " " << next.step << "\n";
				}
 			}
 			
		}
		
	}
}
int main()
{
	for(int i = 2; i < 10001; i++)
	{
		if(!v[i]) p[cnt++] = i;
		for(int j = 0; j < cnt; j++)
		{
			if(i*p[j] < 10001) v[i*p[j]] = 1;
			if(i % p[j] == 0) break;
		}
	}
	int t;
	cin >> t;
	while(t--)
	{
		cin >> a >> b;
		while(!q.empty()) q.pop();//忘记清空队列  一直wa
		//memcpy(vis,v,sizeof(v));
		memset(vis, 0, sizeof(vis));
		sz st;
		st.s = a;
		st.step = 0;
		q.push(st);
		bfs();
	}
	/*for(int i = 2; i < 10001; i++)
	cout << i << " " << v[i] << "\n";*/
	
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值