【洛谷P1001】A+B Problem

友链

瞎吹系列

Link: 浅谈O(1)飞天排序及Sleep函数对程序的优化color{red} exttt{Link: }color{blue} exttt{浅谈O(1)飞天排序及Sleep函数对程序的优化}


题目大意:

题目链接:https://www.luogu.org/problemnew/show/P1001
给出a,ba,b两个数,输出a+ba+b


思路:

caijiZYC exttt{caijiZYC} 1秒后才开始学C++。
这道题大部分人的代码都是这样的

#include <cstdio>
using namespace std;
int a,b;
int main(){
    scanf("%d%d",&a,&b);
    printf("%d",a+b);
    return 0;
}

无可否认,这种方法是在是太慢了。时间复杂度竟然高达O(1)O(1)
于是caijiZYC exttt{caijiZYC}决定优化A+B ProblemA+B Problem的代码!
我们把AABB化为二进制,我们发现,在进行A+BA+B时,如果A,BA,B在二进制下的某一位都为00,那么把这两位加起来是十分浪费时间的!所以我们可以把这种情况直接continuecontinue掉,这样就可以优化时间!
这样的话,时间复杂度就被caijiZYC exttt{caijiZYC}降低到了O(log2n)O(log_2 n)

#include <cstdio>
#include <algorithm>
using namespace std;

const int LG=30;
int a,b,c,fa,fb;

int main()
{
	scanf("%d%d",&a,&b);
	fa=(a>=0?1:-1);
	fb=(b>=0?1:-1);
	a=abs(a); b=abs(b);
	for (int i=0;i<=LG;i++)
	{
		if (!(a&(1<<i)) && !(b&(1<<i))) continue;
		if (a&(1<<i)) c+=(1<<i)*fa;
		if (b&(1<<i)) c+=(1<<i)*fb;
	}
	printf("%d
",c);
	return 0;
}

这样的话,程序就会大大加快,甚至在洛谷上跑0ms0ms
在这里插入图片描述
设想一下,如果我们把A,BA,B转化为三进制,那么我们的时间复杂度就为O(log3n)O(log_3 n),四进制的话就是O(log4n)O(log_4 n)。这样下去,如果我们把AABB都化成infty进制的话,时间复杂度就是O(logn)O(log_{infty} n)了!
只要我们设infty足够大,那么O(logn)O(log_{infty} n)就会无限趋近于O(0)O(0),就使得A+B ProblemA+B Problem的程序的复杂度小于O(1)O(1)
caijiZYC exttt{caijiZYC}不愧是一个菜鸡!这么傻逼的东西都能瞎扯出来!
本文纯属搞笑,请勿当真!

原文地址:https://www.cnblogs.com/hello-tomorrow/p/11997971.html