POJ 3126 / Northwestern Europe 2006 Prime Path (数论&BFS)

保姆级教程:手把手教你下载和配置Waymo自动驾驶数据集(附百度网盘链接) 本文提供了一份详细的Waymo自动驾驶数据集下载和配置指南,特别针对国内研究者优化了数据获取方案,包括百度网盘链接和Google Cloud CLI配置。文章还涵盖了环境配置、数据处理实战、可视化分析以及进阶技巧,帮助开发者高效利用这一业界黄金标准数据集进行自动驾驶研究。 阅读详情
Prime Path

Time Limit:  1000MS
Memory Limit: 65536K

Description

The ministers of the cabinet were quite upset by the message from the Chief of Security stating that they would all have to change the four-digit room numbers on their offices. 
— It is a matter of security to change such things every now and then, to keep the enemy in the dark. 
— But look, I have chosen my number 1033 for good reasons. I am the Prime minister, you know! 
— I know, so therefore your new number 8179 is also a prime. You will just have to paste four new digits over the four old ones on your office door. 
— No, it’s not that simple. Suppose that I change the first digit to an 8, then the number will read 8033 which is not a prime! 
— I see, being the prime minister you cannot stand having a non-prime number on your door even for a few seconds. 
— Correct! So I must invent a scheme for going from 1033 to 8179 by a path of prime numbers where only one digit is changed from one prime to the next prime. 

Now, the minister of finance, who had been eavesdropping, intervened. 
— No unnecessary expenditure, please! I happen to know that the price of a digit is one pound. 
— Hmm, in that case I need a computer program to minimize the cost. You don't know some very cheap software gurus, do you? 
— In fact, I do. You see, there is this programming contest going on... Help the prime minister to find the cheapest prime path between any two given four-digit primes! The first digit must be nonzero, of course. Here is a solution in the case above. 
1033
1733
3733
3739
3779
8779
8179
The 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.

Input

One line with a positive number: the number of test cases (at most 100). Then for each test case, one line with two numbers separated by a blank. Both numbers are four-digit primes (without leading zeros).

Output

One line for each case, either with a number stating the minimal cost or containing the word Impossible.

Sample Input

3
1033 8179
1373 8017
1033 1033

Sample Output

6
7
0

提示:使用一个结构保存数和路径长度。
处理4位数也可以使用字符串,详见这篇文章。

完整代码:
/*0ms,160KB*/
///还可以设计一个保存搜索结果的算法

#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;

int m, n;
bool pr[10000],vis[10000];
struct st
{
	int x, v;
	st(int xx, int vv): x(xx), v(vv) {}
};

inline void init()
{
	for (int i = 2; i < 100; i++)
		if (!pr[i])
			for (int j = i * i; j < 10000; j += i)
                pr[j] = true;
}

inline int bfs()
{
	memset(vis, 0, sizeof(vis));
	queue<st> q;
	q.push(st(m, 0));///起点
	vis[m] = true;
	while (!q.empty())
	{
		st u = q.front();
		q.pop();
		for (int t = 1; t <= 1000; t *= 10)
		{
			int a = (u.x / t) % 10;
			int b = (u.x - a * t);
			for (int j = 0; j < 10; j++)
			{
				int c = b + j * t;///精妙的设计
				if (vis[c] || pr[c] || j == a || (t == 1000 && j == 0))///千位不能是0
                    continue;
				if (c == n)///到终点了
                    return u.v + 1;
				q.push(st(c, u.v + 1));
				vis[c] = true;
			}
		}
	}
	return -1;
}

int main()
{
	init();
	int t;
	scanf("%d", &t);
	while (t--)
	{
		scanf("%d%d", &m, &n);
		int ans = (m != n ? bfs() : 0);
		if (~ans)
			printf("%d\n", ans);
		else
			puts("Impossible");
	}
	return 0;
}


OpenCode + Oh My OpenCode:打造你的终极AI编程团队(OpenCode新手入门指南) 本文详细介绍了开源终端AI编程助手 OpenCode 的完整配置教程 🖥️,从安装、AI模型配置到增强插件 Oh My OpenCode 的部署一应俱全。支持 Claude、ChatGPT、Gemini 多模型切换 🤖,还能实现多AI智能体协作开发。步骤清晰适合新手 📝,想在终端用AI写代码的开发者不要错过 ✨ 阅读详情

相关推荐

AG16K MCU ARM Cortex M3

其中,Input文件为Keil生成的mcu程序文件,输出为合成后的存储格式Bin文件,Program address 为上方表格中“程序运行 RAM 地址(4bytes)”,即 Keil 中设置的程序运行地址。其中 MCU 程序的地址,根据 mcu.ip 中设置的 FLASH_BIAS 进行设置。AG16K MCU 的 FPGA 工程中,需调用 alta_mcu_m3 的硬核 IP,包含在 alta_sim.v 的库文。Quartus II。//MCU 程序在 FLASH 中存放的首地址。

Embeded_FPGA的博客 1806

E - Prime Path

The ministers of the cabinet were quite upset by the message from the Chief of Security stating that they would all have to change the four-digit room numbers on their offices. — It is a matter of sec...

qq_44134712的博客 499

STM32CubeIDE离线安装芯片PACK包全攻略(附离线包下载与导入步骤)

本文详细介绍了在STM32CubeIDE中离线安装芯片PACK包的完整流程,包括官方和第三方资源获取方法、本地安装步骤及常见问题解决方案。特别针对网络隔离环境下的嵌入式开发需求,提供了实用的版本管理和自动化部署技巧,帮助开发者高效完成芯片固件支持包的离线配置。

weixin_30825581的博客 302

【简单搜索】 POJ 3126 Prime Path详解

Prime Path: 题目链接:https://vjudge.net/problem/POJ-3126 The ministers of the cabinet were quite upset by the message from the Chief of Security stating that they would all have to change the four-digit room numbers on their offices. — It is a matter of sec

Qiuker_jl的博客 1603

尚硅谷 Vue2.0 + Vue3.0 入门到精通教程学习笔记 (一)

本文为总结尚硅谷Vue2.0+Vue3.0 的学习笔记系列的第一章——Vue的核心,包含Vue简介、模板语法、数据绑定、MVVM模型、事件处理,计算属性与监视、class与style绑定、列表渲染、过滤器、内置指定和自定义指令以及Vue生命周期等知识点

weixin_44566194的博客 3655

Windows 10/11下R与RStudio最新版安装避坑指南(含镜像加速配置)

本文提供了Windows 10/11系统下R与RStudio最新版的详细安装指南,包含镜像加速配置和常见问题解决方案。通过分步教程帮助用户避开安装陷阱,优化开发环境设置,特别适合国内用户快速搭建高效的数据分析平台。

weixin_29065959的博客 1006

E - Prime Path(BFS+埃式筛)

E - Prime Path 题目 The ministers of the cabinet were quite upset by the message from the Chief of Security stating that they would all have to change the four-digit room numbers on their offices. — It is a matter of security to change such things every now

Mr.RainsdRop的胡思乱想 1336

2024年下半年软考系统架构设计师案例分析题

摘要: 本文包含两个软件系统设计案例。案例一讨论了大语言模型智能系统的质量属性需求分析,识别了功能性、性能、可靠性等需求,并对比了ping/echo和心跳两种故障检测策略。案例二探讨了购物网站的缓存设计,包括Cache-Aside策略的数据读取/更新流程,以及解决缓存一致性的多种方案(消息队列、数据库插件、锁机制等)。此外还涉及Elasticsearch分词器的特点比较和RESTful架构实现前后端分离的原理。这些案例展示了软件架构设计中的质量属性权衡、缓存策略选择及系统解耦等关键技术考量。<|end

卿着飞翔 1047

搜索练习题I-09

The ministers of the cabinet were quite upset by the message from the Chief of Security stating that they would all have to change the four-digit room numbers on their offices.  — It is a matter of s

snayf的博客 409

Android So加载机制分析----基于Android14源码

本文深入分析Android 14系统中SO(共享库)的两种加载机制:System.loadLibrary()和System.load()。前者通过ClassLoader查找标准路径加载,后者直接加载指定路径的SO文件。文档详细追踪了从Java层到动态链接器的完整加载链路,包括ClassLoader路径查找、JNI桥接、ART虚拟机处理以及底层linker的符号解析和重定位过程。同时还分析了Namespace隔离、JNI_OnLoad机制等核心内容,为开发者提供全面的SO加载技术解析和问题排查指南。

保持专注,保持热爱 350

【PostgreSQL】PostgreSQL数据库函数比对模板(PG通用)

LOOKUP 函数从单行或单列区域 (区域:工作表上的两个或多个单元格。区域中的单元格可以相邻或不相邻。)或数组 (数组:用于建立可生成多个结果或可对在行和列中排列的一组参数进行运算的单个公式。数组区域共用一个公式;数组常量是用作参数的一组常量。LOOKUP 函数具有两种语法形式:向量形式和数组形式。vlookup查找匹配值超过255个字符显示#Value的解决办法。如果值为错误值 #N/A,则返回 TRUE。

tttzzzqqq2018的博客 1494

ayit第十四周训练f题

The ministers of the cabinet were quite upset by the message from the Chief of Security stating that they would all have to change the four-digit room numbers on their offices. — It is a matter of security to change such things every now and then, to keep

m0_46628834的博客 565

SAP Fiori Launchpad 概述

SAP Fiori launchpad 是托管 SAP Fiori 应用程序的 shell,并为应用程序提供导航、个性化、嵌入式支持和应用程序配置等服务。SAP Fiori Launchpad 是移动和桌面设备上 SAP Fiori 应用程序的入口点。启动板显示带有图块的主页,其中可以显示实时状态指示器,例如打开的任务数量。每个图块代表用户可以启动的业务应用程序。这包括 SAP Business Suite 事务应用程序和 SAP Smart Business 分析应用程序。

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 932

寒假前刷题(6)广度优先搜索 poj 3126

Prime Path Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 8097   Accepted: 4610 Description The ministers of the cabinet were quite upset by the message from

hange_db的专栏 764

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

poj---3126

Description The ministers of the cabinet were quite upset by the message from the Chief of Security stating that they would all have to change the four-digit room numbers on their offices.  —

qq_35030023的博客 257

VC中sqlite的使用

在VC中对sqlite的使用,实现数据库大批数据的快速插入,读取数据库中的数据在ListCtrl中显示

搜索(队列)

1.引入库 The ministers of the cabinet were quite upset by the message from the Chief of Security stating that they would all have to change the four-digit room numbers on their offices. — It is a matter of security to change such things every now and then...

weixin_52914088的博客 496

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Prime Path(BFS)

The ministers of the cabinet were quite upset by the message from the Chief of Security stating that they would all have to change the four-digit room numbers on their offices. — It is a matter of

lidafoye的博客 331

F - Prime Path

The ministers of the cabinet were quite upset by the message from the Chief of Security stating that they would all have to change the four-digit room numbers on their offices. — It is a matter of security to change such things every now and then, to keep

默的博客 425

1646. Prime Path

单点时限: 2.0 sec 内存限制: 256 MB The ministers of the cabinet were quite upset by the message from the Chief of Security stating that they would all have to change the four-digit room numbers on their offic...

Cuibaby的博客 258

【 POJ - 3126 】 D - Prime Path (BFS)

The ministers of the cabinet were quite upset by the message from the Chief of Security stating that they would all have to change the four-digit room numbers on their offices. — It is a matter of security to change such things every now and then, to keep

黑桃 277

POJ - Prime Path(BFS)

题目链接:http://poj.org/problem?id=3126Time Limit:1000MSMemory Limit:65536K Description The ministers of the cabinet were quite upset by the message from the Chief of Security stating that they would...

ityanger的技术栈 2820

POJ 3126 - Prime Path

Source Northwestern Europe 2006     这道题用的是bfs,求最短路径,因为不是二维表,一开始还想不懂用bfs怎么求,后来想想那就把出发点想成球心,下一个点想成球面,每向下一个点,球面就扩大,选择出能到达终点的路径中最小的球面就相当于求最短路径了。 作出的优化: 预先生成一张素数表 因为是素数,所以最后一位一定为奇数 #i...

JWind的博客 152

【BFS】POJ 3126 Prime Path

Problem Description 输入T组数据,每组数据对应两个千位的素数,要你操作左边的素数变成右边的素数最少的变换(只能改变一个数字,而且变换成的数一定得是素数)次数。 代码:需要注意的点就是,个位数肯定不能是偶数,千位数肯定不能是0#include<cstdio> #include<cstring> #include<queue> using namespace std; queue

ACMer 梁剑锋 的博客 490

POJ - 3126  Prime Path【图论bfs】

Prime Path POJ - 3126 The ministers of the cabinet were quite upset by the message from the Chief of Security stating that they would all have to change the four-digit room numbers on their office...

Puya的博客 309

F - Prime Path (bfs)

The ministers of the cabinet were quite upset by the message from the Chief of Security stating that they would all have to change the four-digit room numbers on their offices. — It is a matter of se

梦初始的地方,它也需要生根发芽。 750

F - Prime Path //BFS 广度优先搜索

F - Prime Path The ministers of the cabinet were quite upset by the messa...

LMengi000的博客 362
上一篇: POJ 1033 / Northeastern Europe 1998 Defragment (模拟&队列)
下一篇: Codeforces Round #131 (Div. 2) / 214A System of Equations(枚举&优化)
synapse7
博客等级 码龄14年 432粉丝 701原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值