码迷,mamicode.com
首页 > 其他好文 > 详细

fzu 2058 问题转化 + 二分

时间:2015-05-16 16:35:53      阅读:98      评论:0      收藏:0      [点我收藏+]

标签:

题意

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

fzu 2058 问题转化 + 二分

标签:

原文地址:http://blog.csdn.net/u013382399/article/details/45768695

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!