16/4/17NEFU训练 I 这题没名字 模拟题

题目描述:

Description
Now give you an interger m and a sequence: s[1], s[2], …… , s[N] in not decreasing order. The length of the sequence is n. Your task is to find out how many pair of a and b satisfy a+b=m. Note that each element of the sequence can use once at most.
Input
The input consists of multiple test cases. The first line of each test case contains three integers N(0 < n<=1000000), M(0 < m<=1000000000), which denote the length of the sequence and the sum of a+b, respectively. The next line give n interger(0 < s[i]<=10000000)。 Note the input is huge.
Output
For each case, output the num of pairs in one line.
Sample Input

3 3
1 1 2
3 2
1 1 1
5 5
1 1 2 3 4

Sample Output

1
1
2

题目分析:

n个长度的非递减序列,找出一对元素之和为m,求这个序列中有多少对。(数据较多)
因为有重复数据,在输入序列的时候把相同的数据处理一下(不能删掉)。在第一次出现的相同数据做一标记,标记之后与之相同的有多少个,在最后一次出现的相同数据也做标记,标记之前有多少与之相同的。然后就从前往后同时从后往前找,如果不匹配跳往下一个不同的数据。如果相同,两个”指针”均往中间走。

代码如下:

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
typedef long long ll;
const int INF = 0x3f3f3f3f;

int s[1000010];
int next[1000010];
int pre[1000010];
int m,n;

int main()
{
    while(~scanf("%d%d",&n,&m))
    {
        int l=0,r=n-1;
        memset(s,0,sizeof(s));
        memset(next,0,sizeof(next));
        memset(pre,0,sizeof(pre));
        int tmp;
        scanf("%d",&s[0]);
        tmp=s[0];
        next[0]=1;
        for(int i=1; i<n; i++)
        {
            scanf("%d",&s[i]);
            if (s[i]==tmp) next[i-1]++;
            else {next[i]++;tmp=s[i];}
        }
        pre[n-1]=1;
        tmp=s[n-1];
        for(int i=n-2; i>=0; i--)
        {
            if (s[i]==tmp) pre[i+1]++;
            else {pre[i]++;tmp=s[i];}
        }
        int sum=0;
        while(l<r)
        {
            if (s[l]+s[r]==m)
            {
                sum++;
                l++;r--;
            }
            else if (s[l]+s[r]<m) if (next[l]!=0) l=l+next[l];else l++;
            else if (s[l]+s[r]>m) if (pre[r]!=0) r=r-pre[r];else r--;
            //printf("%d %d\n",l,r);
        }
        printf("%d\n",sum);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值