【51Nod】1001 数组中和等于K的数对
来源:互联网 发布:mac删除下载的软件 编辑:程序博客网 时间:2024/05/02 07:15
题意
给出一个整数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)。
解题思路
先将A进行排序,我们对A中的每个元素查找对应的数对时,可以采用二分查找,因为是顺序排列了。
剪枝:当A中的元素值的两倍大于等于K时,不用继续查找了。
参考代码
#include <iostream>#include <algorithm>using namespace std;#define MAXN 50000+5int a[MAXN];int k,n;int bs(int x){ //二分查找 int l=0,r=n-1; while (l<=r){ int mid=(l+r)/2; if (x<a[mid]) r=mid-1; if (x==a[mid]) return mid; if (x>a[mid]) l=mid+1; } return -1;}int main(){ while (cin>>k>>n){ for (int i=0;i<n;i++) cin>>a[i]; sort(a,a+n); int cnt=0; for (int i=0;i<n;i++){ if (2*a[i]>=k) break; //剪枝 int tmp=bs(k-a[i]); if (tmp!=-1){ cout<<a[i]<<" "<<k-a[i]<<endl; cnt++; } } if (cnt==0) cout<<"No Solution"<<endl; } return 0;}
0 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的数对
- JS判断值是否是数字
- Java匿名内部类使用与示例
- 【LeetCode】7. Reverse Integer
- android 使文字向左或者向右倾斜
- uva Fewest Flops(dp)@
- 【51Nod】1001 数组中和等于K的数对
- Spring中的@Controller注解和@RestController注解的相同点和不同点
- LightOJ1248-Dice (III)
- 工厂方法模式
- 简单拓扑-入门
- 小程序开发系列(五)悬浮搜索框
- 递归类型的二叉树
- XAMPP FTP(FileZilla)使用教程
- 浅谈simhash及其python实现