快读模板(板子总结)

C++快读和快写 虽然读入优化好像用处不大,但是还是能够在读入数据规模较大的时候提供较大的优化,比如:用cin输出2000个100000000用快输输出2000个100000000单位都是毫秒。可以直观的发现,用快输的话输出时间优化了很多,那么快读是如何做到这样的呢? 阅读详情

思路来源

https://blog.csdn.net/balalalalalalala/article/details/81869016

想测快读快不快,nth_element+快读CSU2078来战ORZ,

1e7的数据量配上均值意义的O(n),删了好几个假的快读板子

快读板子

整数读入输出挂

数组空间一般开10W,如果不能fread,把gc改成getchar

缓存空间大减少缓存次数,空间大开空间也需要时间,二者存在tradeoff

绝大多数情况用这种文件读入即可

namespace fastIO
{
    static char buf[100000],*h=buf,*d=buf;//缓存开大可减少读入时间,看题目给的空间
    #define gc h==d&&(d=(h=buf)+fread(buf,1,100000,stdin),h==d)?EOF:*h++//不能用fread则换成getchar
    template<typename T>
    inline void read(T&x)
    {
        int f = 1;x = 0;
        register char c(gc);
        while(c>'9'||c<'0'){
            if(c == '-') f = -1;
            c=gc;
        }
        while(c<='9'&&c>='0')x=(x<<1)+(x<<3)+(c^48),c=gc;
        x *= f;
    }
    template<typename T>
    void output(T x)
    {
        if(x<0){putchar('-');x=~(x-1);}
        static int s[20],top=0;
        while(x){s[++top]=x%10;x/=10;}
        if(!top)s[++top]=0;
        while(top)putchar(s[top--]+'0');
    }
}
using namespace fastIO;

浮点数读入挂

inline bool scan_lf(double &num)  
{
        char in;double Dec=0.1;
        bool IsN=false,IsD=false;
        in=getchar();
        if(in==EOF) return false;
        while(in!='-'&&in!='.'&&(in<'0'||in>'9'))
                in=getchar();
        if(in=='-'){IsN=true;num=0;}
        else if(in=='.'){IsD=true;num=0;}
        else num=in-'0';
        if(!IsD){
                while(in=getchar(),in>='0'&&in<='9'){
                        num*=10;num+=in-'0';}
        }
        if(in!='.'){
                if(IsN) num=-num;
                return true;
        }else{
                while(in=getchar(),in>='0'&&in<='9'){
                        num+=Dec*(in-'0');Dec*=0.1;
                }
        }
        if(IsN) num=-num;
        return true;
}

cin关同步

cin读入的数据总是要放到缓存中,取消同步会快一点

一般都是scanf比cin快,所以平时除了cin>>string的时候好像用不到……

ios::sync_with_stdio(false);
cin.tie(0);cout.tie(0);

FastIO挂

视题目给的空间调整buffer_size的大小,一般开10W

缓存空间大减少缓存次数,空间大开空间也需要时间,二者存在tradeoff

短一点的板子,但略慢

namespace fastIO 
{ 
	#define BUF_SIZE 100000
	bool IOerror = 0; 	
	inline char nc(){ 		
		static char buf[BUF_SIZE],*p1=buf+BUF_SIZE,*pend=buf+BUF_SIZE;
		if(p1==pend){
		    p1=buf; 			
		    pend=buf+fread(buf,1,BUF_SIZE,stdin); 				
		} 		
		return (*p1++); 	
	} 	
	inline int in(){
		char c=nc();
		while(!isdigit(c))c=nc();
		int x=0;
		while(isdigit(c)){
			x=x*10+c-'0';
			c=nc();
		}
		return x;
	}
	#undef BUF_SIZE 
}; 
using namespace fastIO;

长一点的板子,相对来说较快

struct FastIO{
	FILE *fp;
	static const int S=1e5;
	typedef long long ll;
	int wpos;
	char wbuf[S];
	FastIO():wpos(0){}
	inline int xchar(){
		static char buf[S];
		static int len=0,pos=0;
		if(pos==len)pos=0,len=fread(buf,1,S,stdin);
		return buf[pos++];
	}
	inline int xuint(){
		int c=xchar(),x=0;
		while(c<=32)c=xchar();
		for(;'0'<=c&&c<='9';c=xchar())x=x*10+c-'0';
		return x;
	}
	inline int xint(){
		int s=1,c=xchar(),x=0;
		while(c<=32)c=xchar();
		if(c=='-')s=-1,c=xchar();
		for(;'0'<=c&&c<='9';c=xchar())x=x*10+c-'0';
		return x*s;
	}
	inline void xstring(char *s){
		int c=xchar();
		while(c<=32)c=xchar();
		for(;c>32;c=xchar())*s++=c;
		*s=0;
	}
	inline void wchar(int x){
		if(wpos==S)fwrite(wbuf,1,S,stdout);
		wbuf[wpos++]=x;
	}
	inline void wint(ll x){
		if(x<0)wchar('-'),x=-x;
		char s[24];
		int n=0;
		while(x||!n)s[n++]='0'+x%10,x/=10;
		while(n--)wchar(s[n]);
		wchar('\n');
	}
	inline void wstring(const char *s){
		while(*s)wchar(*s++);
	}
	~FastIO(){
		if(wpos)fwrite(wbuf,1,wpos,stdout),wpos=0;
	}
}io;

 

java快读模板 import java.io.*; import java.util.StringTokenizer; class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 阅读详情

相关推荐

C++ Fast IO 快读快输

没啥,就贴个板子。 自从我们开始学 OI 以来,我们就接触了 IO。在 zsjz,老师会说: 大家读入数字都用这个: cin>>n; 输出数字都有这个: cout<<n; 在 zsyz,老师会说: 大家读入数字都用这个: scanf("%d",&n); 输出数字都用这个: printf("%d",n); 效率上,肯定是后面的快,但是前面的如果只加上这一句,就可以和后面达到同样的效果: ios::sync_with_stdio(false); 但有些时候,两个都不行,

Ryan_Right的博客 3581

快读 (快速读入)模板

之所以有快读,是因为getchar()比scanf快了大概4倍听别人说的,不知道准不准确哈。。 但是又由于getchar又只能一个一个字符的读入,所以自己要写个函数,才有了这个称呼。 inline int read() { char c = getchar();int x = 0,s = 1; while(c <= '0' || c >= '9') {if(c == '-') s = -1;c = getchar();}//是符号 while(c >= '0' &a

give it a try 4380

COMSOL仿真避坑指南:列管反应器模拟中多孔介质与化学反应设置的5个常见错误

本文详细解析了COMSOL仿真中列管反应器模拟的5个常见错误,包括多孔介质模型选择、化学反应接口配置、对流扩散方程处理、薄层热阻设置及网格独立性验证。特别针对多孔介质与化学反应设置的误区,提供了实用的判断标准和修正方法,帮助工程师避免计算偏差,提升仿真精度。

weixin_29597551的博客 331

快速排序+速读

#include <bits/stdc++.h> using namespace std; const int N = 5e6 + 20; int t, n, k; int m[N]; int quick_sort(int m[], int l, int r, int k) { if (l >= r) return m[r]; int x = m[l], i = l - 1, j = r + 1; while (i < j) { do i++; while (m[i] < x)

mrgaohaihang的博客 454

摄像机实时接入分析平台视频分析网关AI智能分析智慧营业厅方案

通过智能化的改造,可以提高营业厅的运营效率,降低运营成本,同时提升客户体验和安全保障。

EasyDarwin开源社区技术博客 709

PCIe网卡驱动实现分析(三)--- cache一致性

在现代处理器系统中,CPU的主频远高于主存读写速度,主存的读写速度成为程序执行效率的瓶颈;为了解决这个问题,在CPU和主存之间引入了Cache存储器,基于程序执行的局部性原理,在程序执行时,将正在使用的数据从主存拷贝一份到Cache,这样CPU就可以直接从Cache读写数据以改善主存读写速度慢的问题;

a935854743的博客 1781

快写快读板子

在数据类型为long long 或__int128时,需要更改read函数的返回类型已经函数中局部变量x和f的类型。特别需要注意的事:快写快读模板只能操作整数,对于浮点数来说用不了。另一种快读板子是往read里面传入需要读入数据的变量地址。

weixin_62598521的博客 305

优秀的 Verilog/FPGA开源项目介绍(六)- MIPI

MIPI的协议我就不详细介绍了(可以查看<下面的二维码>),这里和开源方案比较接近的即使FPGA实现MIPI物理层(DPHY)中电气属性相关的几种方案:MIPI DPHY RX...

OpenFPGA的博客 4467

做题常用板子(含快读)

【代码】做题常用板子(含快读)

weixin_75192140的博客 324

机器学习算法 —— LightGBM

本次我们选择英雄联盟数据集进行LightGBM的场景体验。英雄联盟是2009年美国拳头游戏开发的MOBA竞技网游,在每局比赛中蓝队与红队在同一个地图进行作战,游戏的目标是破坏敌方队伍的防御塔,进而摧毁敌方的水晶枢纽,拿下比赛的胜利。现在共有9881场英雄联盟韩服钻石段位以上的排位比赛数据,数据提供了在十分钟时的游戏状态,包括击杀数、死亡数、金币数量、经验值、等级……参考项目:机器学习系列入门系列[七]:基于英雄联盟数据集的LightGBM的分类预测。

ZShiJ的博客 712

Android SELinux——neverallow问题处理(十六)

遇到 neverallow 规则问题,千万别急着去注释/剔除里面原有的规则(原生的尽量别动)。增加 allow 规则是常见的解决办法,但是随着 android 版本的升级,系统对 SELinux 的管控越来越严,增加了大量的 neverallow。一般情况下,向默认标签授予权限的做法是错误的,其中许多权限都是 neverallow 规则所不允许的。按照上面方法去添加 SELinux 可能会违反了 neverallow 规则,编译时候会报 neverallow 相关的错误。

小旭的专栏 2701

acm快读模板

orz qscqesze inline ll read() { ll x=0,f=1;char ch=getchar(); while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();} while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();} ...

tomjobs的博客 1150

Open Dynamics Engine(ODE)物理引擎教程(1)--下载与安装准备

引言 ODE是一个免费的工业级库,用于模拟关节式刚体动力学,例如地面车辆、腿部生物和虚拟现实环境中的移动对象。它具有快速、灵活、健壮和独立于平台的特点,具有先进的关节、摩擦接触和内置的碰撞检测功能。 项目主页:http://www.ode.org/ 线上手册:http://ode.org/wiki/index.php?title=Manual 本教程为博主亲自亲测过程的总结,转载请注明出处! ...

腿足机器人领域 2222

快读模板&&快出模板

inline int read() { int X=0,w=1; char c=getchar(); while(c<'0'||c>'9') { if (c=='-') { w=-1; } c=getchar(); ...

weixin_34376562的博客 716

YOLO26改进策略【YOLO和Mamba】| MLLA:Mamba-Like Linear Attention,融合Mamba设计优势的注意力机制

本文记录的是利用模块优化的目标检测网络模型。模块具有独特优势。它不同于传统模块,能同时兼顾局部特征高效建模与长距离交互学习。常见模块要么在局部特征处理上有优势但长距离交互能力弱,要么反之,而模块克服了此问题。它融合了Mamba模型和线性注意力机制的优势,通过独特的结构设计,能够在保持计算效率的同时,精准地建模局部特征并学习长距离交互信息。本文将其用于的模型改进和二次创新,能够更加关注图像中的重要特征区域,抑制背景等无关信息的干扰,从而突出目标物体的关键特征。Demystify Mamba in Vision

Limiiiing的博客 222

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

【板子】快读plus

中间有没有空格、有没有多余空行、Windows。读矩阵,多一个换行就错位;

ysa051030的博客 41

深度学习工具包 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")

快读板子fread

1 struct ios { 2 inline char read(){ 3 static const int IN_LEN=1<<18|1; 4 static char buf[IN_LEN],*s,*t; 5 return (s==t)&&(t=(s=buf)+fread(buf...

dicui07574的专栏 660

efm32 入门.pdf

本PDF共计22页,介绍的是操作驱动API,下载与否自己斟酌。

ACM板子

有3堆各若干个物品,两个人轮流从某一堆取任意多的物品,规定每次至少取1个,多者不限(但不能超过一堆),最后取光者得胜。所以取到(0,0,0,0)就获胜了 ---- 异或和不等零 先手必胜。

GGood_Name的博客 1192

大一蓝桥杯JAVAB组国一算法板子分享

0基础大一半年蓝桥杯JAVAB组国一

2403_86391704的博客 1210

快读快写的艺术

注意!这个人的快读快写真的值得一看!有不一样的思路提供!

georgeyu-CJR的blog 218

bbb的快读模板

ios对cin的加速欺骗了我,md数据量稍微大一点就TLE了,不太靠谱,搞一波bbb群主的快读板子,用于对付卡常用,虽然一般感觉用不到叭,sacnf够用了,但搞上一波没啥坏处 using namespace std; typedef long long ll; #define repi(i,b,e) for (int i = (b), _ = (e); i < _; ++i) #define rep(i,b,e) for (int i = (b), _ = (e); i <= _; ++i)

yangzijiangac的博客 1968

快读板子

template<class T> void read(T &res) { res = 0; char c = getchar(); T f = 1; while(c < '0' || c > '9') { if(c == '-') f = -1; c = get...

weixin_30314631的博客 164

快读快写板子

【代码】快读快写板子。

2401_87428129的博客 29

快读+头文件 模板

//快读+头文件 模板 #include<map> #include<set> #include<cmath> #include<stack> #include<queue> #include<cstdio> #include<vector> #include<cstring> #include&l...

DorisBao1021的博客 450
上一篇: 哈尔滨理工大学第七届程序设计竞赛决赛(网络赛-高年级组)H.字典序最小的中序遍历(树形dp)
下一篇: CSU - 2078 查找第k大(O(n)区间第k大 快排思想)
小衣同学
博客等级 码龄9年 1444粉丝 995原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小衣同学

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值
⌂ 换网址