2 条题解
-
1
- [ ] 暴力枚举的时间复杂度为O(n^4),会超时,因此我们可以开一个哈希表记录第一第二个数组相加的结果,然后枚举第三第四个数组去找有没有对应的值;有的话加上值的个数;
代码如下:
#include<bits/stdc++.h> using namespace std; int arr[4][1005]; int main(){ ios_base::sync_with_stdio(0); cin.tie(0);cout.tie(0); int n;cin>>n; for(int i=0;i<4;i++){ for(int j=0;j<n;j++){ cin>>arr[i][j]; } } //第一次先遍历一二数组并记录 unordered_map<long long,int>hash; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ long long sum=arr[0][i]+arr[1][j]; hash[sum]++; } } long long ans=0; //第二次遍历三四数组找答案 for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ long long sum=arr[2][i]+arr[3][j]; if(hash[sum])ans+=hash[sum];//找到对应值后加上个数 } } if(ans)cout<<ans; else cout<<"all in"; return 0; }
时间复杂度O(n^2) 空间复杂度O(n)
- 1
信息
- ID
- 876
- 时间
- 2000ms
- 内存
- 256MiB
- 难度
- 8
- 标签
- 递交数
- 205
- 已通过
- 39
- 上传者