您的位置:首页 > 其它

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

2016-04-17 19:39 288 查看

题目描述:

Description

Now give you an interger m and a sequence: s[1], s[2], …… , s
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: