51nod 1001 数组中和等于K的数对
来源:互联网 发布:如何开通淘宝客 编辑:程序博客网 时间:2024/05/17 02:29
1001 数组中和等于K的数对
基准时间限制:1 秒 空间限制:131072 KB 分值: 5 难度:1级算法题
收藏
关注
给出一个整数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-165342908
Output示例
-1 90 82 63 5
题意:中文
思路:要找相加为k的数对,本菜的思路是先排序,然后从头到尾进行取值用二分查找它的另一半,使用过的数据标记一下
(貌似不用二分查找也能过,但是二分的话明显提高效率)
#include <iostream>#include<cstdio>#include<string.h>#include<algorithm>using namespace std;const int maxn=5e4+10;int k,n;int a[maxn],b[maxn];int tmp;//采用二分搜索解决bool solve(int i){ int lb=-1,ub=n; while(ub-lb>1) { int mid=(lb+ub)/2; if(a[mid]+i>k) { ub=mid; } else if(a[mid]+i<k) { lb=mid; } else if(a[mid]+i==k) { b[mid]=1; tmp=a[mid]; return true; } } return false;}int main(){ cin>>k>>n; int flag=0; for(int i=0;i<n;i++) { cin>>a[i]; } sort(a,a+n); for(int i=0;i<n;i++) { if(b[i]==0&&solve(a[i])) { if(a[i]==tmp)continue; flag=1; cout<<a[i]<<" "<<tmp<<endl; } } if(flag==0)cout<<"No Solution"<<endl; return 0;}
阅读全文
1 0
- 51nod 1001 数组中和等于K的数对
- 51Nod 1001 数组中和等于K的数对
- 51Nod 1001 数组中和等于K的数对
- 51nod 1001 数组中和等于K的数对
- 51nod 1001 数组中和等于K的数对
- 51nod-1001 数组中和等于K的数对
- 51nod-【1001 数组中和等于K的数对】
- 51nod 1001 数组中和等于K的数对
- 51nod 1001 数组中和等于K的数对
- 51NOD 1001 数组中和等于K的数对
- 51nod 1001 数组中和等于K的数对
- 51Nod 1001 数组中和等于K的数对
- 【51Nod】1001 数组中和等于K的数对
- 51NOD 1001数组中和等于K的数对
- 51Nod--1001 数组中和等于K的数对
- 51Nod 1001 数组中和等于K的数对
- 51nod 1001 数组中和等于K的数对
- 51nod 1001 数组中和等于K的数对
- QT的exe文件移植到其他机器非png图片操作问题
- rpm包和tar包安装的mysql启动/关闭上存在不同
- 走迷宫
- 【Unity游戏开发】浅谈Unity游戏开发中的单元测试
- HDU 5738 Eureka (共线点集 组合数)
- 51nod 1001 数组中和等于K的数对
- Java 中Timer和TimerTask 定时器和定时任务使用的例子
- jQuery选择器总结
- 文章标题
- c++指针中0,NULL和nullptr
- A Boring Question HDU
- ThreadLocal
- H.264中I帧和IDR帧的区别
- PAT乙级1048. 数字加密(20)