AcWing 1221. 四平方和

原题链接

考察:hash

思路:

        正常是四重for循环枚举,但是由时间复杂度而言我们只能枚举2个数,此时考虑用空间换时间:预处理平方和.

 1 #include <iostream>
 2 #include <cstring>
 3 #include <algorithm>
 4 using namespace std;
 5 const int N = 2500,M = 5*1e6;
 6 typedef pair<int,int> PII;
 7 int h[N],cnt;
 8 PII p[M];
 9 bool st[M];
10 void inits()
11 {
12     for(int i=1;i<=M/i;i++)
13         h[i] = i*i,cnt++;
14     for(int i=0;i<=cnt;i++)
15       for(int j=0;j<=cnt;j++)
16       {
17           if(h[i]+h[j]>=M||st[h[i]+h[j]]) continue;
18           st[h[i]+h[j]] = 1;
19           p[h[i]+h[j]].first = i,p[h[i]+h[j]].second =  j;
20       }
21 }
22 int main()
23 {
24     int n;
25     scanf("%d",&n);
26     inits();
27     for(int a=0;a<=cnt;a++)
28       if(h[a]<n)
29       for(int b = a;b<=cnt;b++)
30         if(h[a]+h[b]<n)
31         {
32             int sum = n-h[a]-h[b];
33             if(!st[sum]) continue;
34             int c = p[sum].first,d = p[sum].second;
35             if(c>d) swap(c,d);
36             printf("%d %d %d %d\n",a,b,c,d);
37             return 0;
38         }
39     return 0;
40 }

 

posted @ 2021-02-24 14:11  acmloser  阅读(79)  评论(0编辑  收藏  举报