AcWing 1221. 四平方和

暴力法,理论上时间复杂度为O(N3)

但是实际上,时间反而最短 超时

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <cmath>

using namespace std;

const int N = 2500010;

int n;


int main()
{
    cin >> n;

    for (int a = 0; a * a < n; a++) {
        for (int b = a; a * a + b * b <= n; b++) {
            for (int c = b; a * a + b * b + c * c <= n; c++) {
                int t = n - a * a - b * b - c * c;
                int d = sqrt(t);
                if (d * d == t) {
                    printf("%d %d %d %d\n", a, b, c, d);
                    return 0;
                }
            }
        }
    }

}

哈希表 超时

时间复杂度 为O(N2)

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <unordered_map>

#define x first
#define y second

using namespace std;

typedef pair<int, int> PII;

int n;
unordered_map<int, PII> S;


int main()
{
    cin >> n;

    for (int c = 0; c <= n; c++) {
        for (int d = c; c * c + d * d <= n; d++) {
            int t = c * c + d * d;
            if (S.count(t) == 0) S[t] = {c, d};
        }
    }

    for (int a = 0; a <= n; a++) {
        for (int b = a; a * a + b * b <= n; b++) {
            int t = n - a * a - b * b;
            if (S.count(t)) {
                printf("%d %d %d %d\n", a, b, S[t].x, S[t].y);
                return 0;
            }
        }

    }

    return 0;
}

二分法 O(N2logN) 2691 ms

关键是运算符的重载不会

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <cmath>

using namespace std;

const int N = 2500010;

struct Sum
{
    int s, c, d;
    bool operator< (const Sum &t)const
    {
        if (s != t.s) return s < t.s;
        if (c != t.c) return c < t.c;
        return d < t.d;
    }
}sum[N];

int n,m;

int main()
{
    cin >> n;

    for (int c = 0; c * c <= n; c++) {
        for (int d = c; c * c + d * d <= n; d++) {
            sum[m++] = {c * c + d * d, c, d};
        }
    }

    sort(sum, sum + m);

    for (int a = 0; a * a <= n; a++) {
        for (int b = 0; a * a + b * b <= n; b++) {
            int t = n - a * a - b * b;
            int l = 0, r = m - 1;
            while(l < r) {
                int mid = l + r >> 1;
                if (sum[mid].s >= t) r = mid;
                else l = mid + 1;
            }
            if (sum[l].s == t) {
                printf("%d %d %d %d\n", a, b, sum[l].c, sum[l].d);
                return 0;
            }
        }
    }

    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值