51nod 1001 数组中和等于k的数对(单调性优化)

给出一个整数K和一个无序数组A,A的元素为N个互不相同的整数,找出数组A中所有和等于K的数对。例如K = 8,数组A:{-1,6,5,3,4,2,9,0,8},所有和等于8的数对包括(-1,9),(0,8),(2,6),(3,5)。
 
Input
第1行:用空格隔开的2个数,K N,N为A数组的长度。(2 <= N <= 50000,-10^9 <= K <= 10^9)
第2 - N + 1行:A数组的N个元素。(-10^9 <= A[i] <= 10^9) 
Output
第1 - M行:每行2个数,要求较小的数在前面,并且这M个数对按照较小的数升序排列。
如果不存在任何一组解则输出:No Solution。
Input示例
8 9
-1
6
5
3
4
2
9
0
8
Output示例
-1 9
0 8
2 6
3 5

二分也可。
不过单调性优化可以直接复杂度到O(n)
 1 /*************************************************************************
 2     > File Name: code/51nod/1001.cpp
 3     > Author: 111qqz
 4     > Email: rkz2013@126.com 
 5     > Created Time: 2015年10月19日 星期一 18时31分13秒
 6  ************************************************************************/
 7 
 8 #include<iostream>
 9 #include<iomanip>
10 #include<cstdio>
11 #include<algorithm>
12 #include<cmath>
13 #include<cstring>
14 #include<string>
15 #include<map>
16 #include<set>
17 #include<queue>
18 #include<vector>
19 #include<stack>
20 #include<cctype>
21                  
22 #define yn hez111qqz
23 #define j1 cute111qqz
24 #define ms(a,x) memset(a,x,sizeof(a))
25 using namespace std;
26 const int dx4[4]={1,0,0,-1};
27 const int dy4[4]={0,-1,1,0};
28 typedef long long LL;
29 typedef double DB;
30 const int inf = 0x3f3f3f3f;
31 const int N=5E4+7;
32 int k,n;
33 int a[N];
34 int main()
35 {
36   #ifndef  ONLINE_JUDGE 
37    freopen("in.txt","r",stdin);
38   #endif
39 
40    scanf("%d %d",&k,&n);
41    for ( int i = 0 ; i < n ; i ++) scanf("%d",&a[i]);
42    sort(a,a+n);
43    int j = n-1;
44    bool flag = false;
45    for ( int i = 0 ; i < n-1 ; i++)
46    {
47        while (i<j&&a[i]+a[j]>k) j--;
48        if (a[i]+a[j]==k&&i<j)
49        {
50        flag = true;
51 //       cout<<"i:"<<i<<" j:"<<j<<endl;
52        printf("%d %d\n",a[i],a[j]);
53        }
54    }
55    if (!flag) puts("No Solution");
56   
57    
58  #ifndef ONLINE_JUDGE  
59   fclose(stdin);
60   #endif
61     return 0;
62 }
View Code

 

posted @ 2015-10-19 18:47  111qqz  阅读(293)  评论(0编辑  收藏  举报