I should use hash for the question of the 11386 Triples of the uva, and use STL map to time out. But I wrote two parts by hand and added some optimization. The time limit is 8 seconds. I got stuck in 7.8 seconds. It's great!
This question has been played many times. It is worth noting that ans does not use enough int. In the end, it will be changed to long because the data in this question does not have a range and is only a positive integer, so it's a bit uncomfortable... However, ans can calculate that it is definitely more than int, because there are a maximum of 5000 numbers. If there are 1000 1 1000 2 3000 3, the answer is that 3e9 exceeds int.
#include <iostream> #include <cstdio> #include <map> #include <vector> #include <algorithm> using namespace std; const int maxn=5010; long long a[maxn],n; map <long long,int> mp; map <long long,int>::iterator it; vector <long long> v; vector <int> cnt; int binaryS(int left,int c){ int l=left,r=v.size()-1; while(l<r){ int mid=(l+r)/2; if(v[mid]>=c) r=mid; else l=mid+1; } return r; } int main(){ while(scanf("%d",&n)!=EOF){ long long int ans=0; mp.clear();v.clear();cnt.clear(); for(int i=0;i<n;i++){ scanf("%lld",&a[i]); mp[a[i]]++; } for(it=mp.begin();it!=mp.end();it++){ v.push_back(it->first); cnt.push_back(it->second); } sort(a,a+n); for(int i=0;i<n;i++){ int left=0; for(int j=i+1;j<n;j++){ long long sum=a[i]+a[j]; int pos=binaryS(left,sum); if(v[pos]!=sum) continue; ans+=cnt[pos]; left=max(pos-1,left); } } cout<<ans<<endl; } return 0; } #include <iostream>#include <cstdio>#include <map>#include <vector>#include <algorithm>using namespace std;const int maxn=5010;long long a[maxn],n;map <long long,int> mp;map <long long,int>::iterator it;vector <long long> v;vector <int> cnt;int binaryS(int left,int c){ int l=left,r=v.size()-1; while(l<r){ int mid=(l+r)/2; if(v[mid]>=c) r=mid; else l=mid+1; } return r;}int main(){ while(scanf("%d",&n)!=EOF){ long long int ans=0; mp.clear();v.clear();cnt.clear(); for(int i=0;i<n;i++){ scanf("%lld",&a[i]); mp[a[i]]++; } for(it=mp.begin();it!=mp.end();it++){ v.push_back(it->first); cnt.push_back(it->second); } sort(a,a+n); for(int i=0;i<n;i++){ int left=0; for(int j=i+1;j<n;j++){ long long sum=a[i]+a[j]; int pos=binaryS(left,sum); if(v[pos]!=sum) continue; ans+=cnt[pos]; left=max(pos-1,left); } } cout<<ans<<endl; } return 0;}