众所周知,很多OIer都想要有 的暴力算法,那么你可以用下面的方法来优化你的暴力,这样你就可以得到一个常数巨大并且特别废手的 暴力
注意事项
- 此专栏纯娱乐,实际“优化”后的代码虽然确实理论上是常数,但是运行效率甚至劣于原来
- 这里都假设值域较小,值域很大的话代码会特别长
- 真要用的话请善用复制粘贴
Part 1. 把for循环变成
相信很多人刚开始学循环的时候都看到过类似这样的表述:
如果要输出 次
Hello那么你需要这么写C++ cout<<"Hello\n"; cout<<"Hello\n"; cout<<"Hello\n"; cout<<"Hello\n"; cout<<"Hello\n";但是次数多了就要写很多的代码,所以我们可以使用
for循环来减少代码C++ for(int i=1;i<=5;i++){ cout<<"Hello\n"; }
那么反过来,我们可以把这样的for循环代码
for(int i=1;i<=5;i++){
cout<<"Hello\n";
}写成这样:
cout<<"Hello\n";
cout<<"Hello\n";
cout<<"Hello\n";
cout<<"Hello\n";
cout<<"Hello\n";那么如果这里不是 遍,而是 n 遍,这里假设 n 的值域为 ,那么我们就可以写出这样的代码:
if(n<=1){
cout<<"Hello\n";
}
if(n<=2){
cout<<"Hello\n";
}
if(n<=3){
cout<<"Hello\n";
}
if(n<=4){
cout<<"Hello\n";
}
if(n<=5){
cout<<"Hello\n";
}Part 2. 把while循环变成
原理同上,这里就可以把下面的while循环代码:
int t;
cin>>t;
while(t--){
cout<<"QwQ\n";
}优化成这样(假设t的值域还是 ,即最多循环 次):
int t;
cin>>t;
if(t--){
cout<<"QwQ\n";
}
if(t--){
cout<<"QwQ\n";
}
if(t--){
cout<<"QwQ\n";
}
if(t--){
cout<<"QwQ\n";
}
if(t--){
cout<<"QwQ\n";
}Part 3. 把递归变成
众所周知,递归是基于栈的,栈保存了每层递归时的所有变量,我们可以用结构体统一维护这些变量,并且用stack来存储:
struct node{
int a,b,c;//函数里面产生的所有变量
};然后用很多代码来模拟递归:
递归版:
void dfs(int stp,int c){
if(stp>1){
return;
}
cout<<c<<endl;
dfs(stp+1,c);
dfs(stp+1,c+1);
}优化版:
struct node{
int stp,c;
}
stack<node>stk;
node x;
x=stk.top();
stk.pop()
if(stp<=1){
cout<<x.c<<endl;
stk.push({x.stp+1,x.c});
stk.push({x.stp+1,x.c+1});
}
//省略一大堆一样的代码,次数就是最多递归的次数
x=stk.top();
stk.pop()
if(stp<=1){
cout<<x.c<<endl;
stk.push({x.stp+1,x.c});
stk.push({x.stp+1,x.c+1});
}