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

YOLO详解 本文参考知乎 https://zhuanlan.zhihu.com/p/25236464 1. YOLO的创新点 YOLO将物体检测作为回归问题求解。基于一个单独的end-to-end网络,完成从原始图像的输入到物体位置和类别的输出。 从网络设计上,YOLO与two steps的目标检测方法如RCNN、Fast RCNN和Faster RCNN的区别如下: YOLO训练和检测均是在一个单独网... 阅读详情
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;
}


【系统架构设计师-2024下半年真题】案例分析-参考答案及部分详解(完整回忆版) 根据h中描述,为了保证高可靠性,有ping/echo,心跳机制两种策略,从资源利用率问为啥心跳更好。王工觉得使用ping/echo好,但李工觉得从系统资源利用率来说,使用心跳机制好 1、针对质量属性可以使用ping/echo和心跳模式实现,分别简述ping/echo和心跳的实现原理。 2、张工认为心跳策略比较适合,简述为什么? 阅读详情

相关推荐

【Python&RS】Rasterio库安装+基础函数使用教程

Rasterio是一个Python库,专门用于栅格数据的读写操作。它支持多种栅格数据格式,如GeoTIFF、ENVI和HDF5,为处理和分析栅格数据提供了强大的工具。RasterIO适用于各种栅格数据应用,如卫星遥感、地图制作等。这篇文章跟大家介绍一下Rasterio库的安装以及一些基本函数的使用教程,附带源码。

Remote Sensing迷途小书童 1万+

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

Cesium实战:5分钟搞定离线地图与地形加载(附避坑指南)

本文详细介绍了Cesium在内网环境下的离线部署实战方案,重点解决了影像与地形数据的本地加载问题。通过逐步指导项目配置、本地瓦片与自定义地形数据的处理,并优化相机控制体验,帮助开发者快速构建安全、高效的三维地球应用,避免常见的401错误与加载失败陷阱。

weixin_30632089的博客 281

【简单搜索】 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

LMS Virtual.Lab二次开发:声学仿真结果导出方法(VBScript、Python)

Siemens LMS Virtual.Lab 提供一套集成软件平台用以模拟机械系统的品质属性,如结构完整性、振动噪声、耐久性、系统动力学特性、驾驶的平顺性及操纵的稳定性等。

爱看书的小沐 6021

YOLOv8工业级增强实战:小目标检测与HDR鲁棒性优化

YOLO(You Only Look Once)作为主流实时目标检测框架,其核心价值在于模块化架构与工程可扩展性。理解YOLOv8的Anchor-Free设计、C2f特征融合机制及Detect头部解耦原理,是实现性能突破的基础。在工业落地中,真实瓶颈往往不是模型版本迭代,而是小目标漏检、高动态范围(HDR)场景适应差、密集遮挡ID断裂等具体问题。通过配置层动态多尺度训练、物理感知数据增强、Neck跨尺度注意力注入、质量感知损失函数升级等七层增强策略,可在不更换主干的前提下显著提升mAP与边缘设备推理效率。本

weixin_32667439的博客 259

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

YOLOv8傻瓜式教程

YOLOv8傻瓜式教程,附带详细参数配置。

Father_of_Python的博客 1万+

搜索练习题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

PaddleOCR SVTRv2中文识别模型训练全流程:从数据准备到推理部署

本文详细介绍了基于PaddleOCR的SVTRv2中文识别模型从数据准备、模型训练到推理部署的全流程实战。SVTRv2凭借其单视觉Transformer架构和分层混合机制,在中文文字识别任务上实现了高精度与效率的平衡。文章重点解析了数据工程、训练调优技巧及部署优化方案,帮助开发者构建定制化的OCR解决方案。

weixin_29194817的博客 287

基于Python的MOOC课程评价爬取与分析系统设计与实现

本文详细介绍了如何使用Python最新技术栈构建一个高效的MOOC课程评价爬取与分析系统。系统采用Scrapy框架结合Selenium实现动态页面抓取,利用PyMySQL进行数据存储,并通过Pandas和Matplotlib实现数据可视化分析。文章从爬虫原理、技术选型、系统设计到代码实现进行全面讲解,为教育工作者改进教学质量提供数据支持。关键词:Python爬虫、MOOC评价分析、Scrapy框架、数据可视化、教学改进。

2201_76125261的博客 1103

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

YOLOv11 改进 - 特征融合 | 小目标检测救星:DySample动态上采样减少特征丢失

本文介绍了超轻量且高效的动态上采样器DySample与YOLOv11的结合,以解决传统上采样器工作负载大、应用场景受限的问题。DySample从点采样角度构建上采样,绕过动态卷积,使用PyTorch标准内置函数实现,无需定制CUDA包,能大幅减少参数、FLOPs等资源消耗。我们将DySample代码集成进YOLOv11。实验脚本显示,结合DySample的YOLOv11在多个密集预测任务中或表现出色。

魔改工程师的博客 1416

寒假前刷题(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

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

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

华为的C语言编程规范.pdf

华为技术有限公司内部技术规范。本规范制定了编写C语言程序的基本原则、规则和建议。从代码的清晰、简洁、可测试、安全、程序效率、可移植各个方面对C语言编程作出了具体指导。

搜索(队列)

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、付费专栏及课程。

余额充值