《论重载运算符的强大性能》

· · 算法·理论

加法

struct node {
    int v;
};
node operator +(const node& a,const node& b) {
    node res;
    res.v=0;
    for(int i=1; i<=a.v; i++)res.v++;
    for(int j=1; j<=b.v; j++)res.v++;
    return res;
}//龟速加

使用经过这个东西加速“优化”的程序,在运行最朴素的加法时,时间复杂度可以来到优秀的O(a+b)。

signed main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    node a,b,c;
    cin>>a.v>>b.v;
    clock_t start = clock();
    c=a+b;
    cout<<c.v<<"\n";
    clock_t end = clock();
    double cpu_time_used = static_cast<double>(end - start) / CLOCKS_PER_SEC;
    std::cout << "CPU time used: " << cpu_time_used << " s\n";

    return 0;
}

我们输入一组较大的数据如a=1000000000,b=1000000000,程序所运行时间来到了4.235s!

乘法

node operator *(const node& a,const node& b) {
    node res;
    res.v=1;
    for(int i=1; i<=a.v; i++) {
        for(int j=1; j<=b.v; j++)res.v++;
    }
    return res;
}//龟速乘

使用经过这个东西加速“优化”的程序,在运行最朴素的乘法时,时间复杂度可以来到优秀的O(a \times b)。

依旧是上面那组数据,程序运行时间来到了31.7年。

这下,你可以直观感受到重载运算符的魅力了(原本C++内置的加法和乘法用时都是O(1),换句话说几乎用时为0ms)。

总的来说,对于算法萌新,以后一定要在代码前面加上:

struct node {
    int v;
};
node operator *(const node& a,const node& b) {
    node res;
    res.v=1;
    for(int i=1; i<=a.v; i++) {
        for(int j=1; j<=b.v; j++)res.v++;
    }
    return res;
}//龟速乘
node operator +(const node& a,const node& b) {
    node res;
    res.v=0;
    for(int i=1; i<=a.v; i++)res.v++;
    for(int j=1; j<=b.v; j++)res.v++;
    return res;
}//龟速加
int sp(int x,int k) {
    int ans=1;
    for(int i=1; i<=k; i++) {
        ans=ans*x;
    }
    return ans;
}//龟速幂

如此,你的程序以后一定能题题都是最优解!