代码时间与空间分析优化
noip模拟赛爆空间真难受。。。。
空间常数#
1Byte=8bit(位)。KB,MB,TB......采用1024进制。
short | 2字节 | (-215~215) 整数型 |
int | 4字节 | (-231~231) 整数型 |
long long | 8字节 | (-263~263) 整数型 |
unsigned long long | 8字节 | [0~264) 整数型 |
char | 1字节 | (0~256) ascll码 |
bool | 1字节 | true(1) 或 false(0) |
float | 4字节 | 单精度浮点数 |
double | 8字节 | 双精度浮点数 |
long double | 未知 | 未知 |
例:int a[1e8]约占381MB(100000000*4/10242)。(考场一般512MB,数组最好不超过1e8)
如何在代码中快速有效计算空间呢?
#include<bits/stdc++.h>
const int maxn=1e7;
using namespace std;
bool st;
int a[maxn];
int b[maxn];
double c[maxn];
bool end;
int main(){
printf("%dMB",(&end-&st)/(1024*1024));
return 0;
}
时间常数优化的一些小trick
1.快读&&快输
int read(){
int s=0,f=1;char c=getchar();
while(c<'0'||c>'9'){if(c=='-')f=-1;c=getchar();}
while(c>='0'&&c<='9'){s=s*10+c-'0';c=getchar();}
return s*f;
}
2.STL的巨大常数(sort除外)so必要时自己手写。
#define min(a,b) (a)<(b)?(a):(b)
#define max(a,b) (a)>(b)?(a):(b)
#define sight(c) ('0'<=c&&c<='9')
#define swap(a,b) a^=b,b^=a,a^=b
bitset:
struct bitsets{
long long t[4];
void set(int x){
int aa,bb;
aa=x/60;bb=x%60;
this->t[aa]|=1LL<<bb;
}
void reset(){
this->t[0]=0;
this->t[1]=0;
this->t[2]=0;
this->t[3]=0;
}
void ad(const bitsets &g){
this->t[0]&=g.t[0];
this->t[1]&=g.t[1];
this->t[2]&=g.t[2];
this->t[3]&=g.t[3];
}
void oo(const bitsets &g){
this->t[0]|=g.t[0];
this->t[1]|=g.t[1];
this->t[2]|=g.t[2];
this->t[3]|=g.t[3];
}
void xo(const bitsets &g){
this->t[0]^=g.t[0];
this->t[1]^=g.t[1];
this->t[2]^=g.t[2];
this->t[3]^=g.t[3];
}
bool tr(const bitsets &g){
bool top=true;
top&=((this->t[0]&g.t[0])==0);
top&=((this->t[1]&g.t[1])==0);
top&=((this->t[2]&g.t[2])==0);
top&=((this->t[3]&g.t[3])==0);
return top;
}
};
3.循环优化。
for (i=1;i<=b;i++)
这样写是很慢的。
for (int i=1;i<=b;i++)
快一丢丢。
4.位运算优化。
if (a^b) 等价于 if (a!=b)
if (!(a^b)) 等价于 if (a==b)
5.多维数组循环。
int a[100001][51];
for(int i=1;i<=50;i++){
for(int j=1;j<=100000;j++){
a[j][i]++;
}
}
慢于
int a[51][100001];
for(int i=1;i<=50;i++){
for(int j=1;j<=100000;j++){
a[i][j]++;
}
}
主要是因为数组的地址是连续的,但连续访问第一维时地址却是跳跃的(更慢)。
比如a[1][1],a[1][2],a[1][3],a[1][4]....a[2][1].
中a[1][1]与a[2][1]的地址相隔甚远。
6.
memset,sizeof,strlen是O(n)的时间复杂度。
length()是O(1)的,但string的运算慢于char数组。
7.使用更快函数
map每次询问是log n的。
但我们可以使用 unordered_map约为O(1)。
以及更快的pb_ds中的hash。用法与map几乎一致。
#include<bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
using namespace std;
using namespace __gnu_pbds;
gp_hash_table<string,int> m;
关键OI考场也能用。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】