题意
A array contain N number, can you tell me how many different pair i,j that satisfy a[i] + a[j] = M and 1<=i < j <=N.
0 < N <= 100000, 0 <= M <= 1000000000, -1000000000 <= a[i] <= 1000000000
思路:
用map记录会超时
所以想到手写二分。思考一下其实满足题目条件的对数和每个数字的位置并没有关系——排序+二分查找(范围来确定个数)即可。
code:
#include<cstdio> #include<iostream> #include<sstream> #include<cstring> #include<algorithm> #include<vector> #include<string> #include<queue> #include<map> #include<set> #include<cmath> #include<cctype> #include<cstdlib> using namespace std; #define INF 0x3f3f3f3f #define PI acos(-1.0) #define mem(a, b) memset(a, b, sizeof(a)) #define mod 1000000007 typedef pair<int,int> pii; typedef long long LL; //------------------------------ const int maxn = 200005; int a[maxn]; int n,m; int Scan(){ int f=1, ret=0; char c; while((c=getchar())==' ' || c=='\n') ; if(c=='-') f=-1; else if(c!='+') ret+=c-'0'; while((c=getchar())<='9' && c>='0') ret=ret*10+c-'0'; return ret*f; } int main(){ while(scanf("%d%d",&n,&m) != EOF){ for(int i = 0; i < n; i++){ a[i] = Scan(); } sort(a,a+n); long long cnt = 0; for(int i = 0; i < n; i++){ int id1 = lower_bound(a+i+1, a+n, m-a[i]) - a; int id2 = upper_bound(a+i+1, a+n, m-a[i]) - a; cnt += (id2 - id1); } cout << cnt << endl; } return 0; }
一TLE吓得我都开挂了....T_T
时间: 2024-10-18 12:35:17