51nod 1001 数组中和等于K的数对
2016-06-11 21:41
281 查看
题目描述:
基准时间限制: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
Output
Input示例
Output示例
解题思路:
由于这道题是未经过排序的,所以可以用set来保存已存在的数据,插入或者删除的时间复杂度为O(logN),需要对每个点都进行这样的操作,因此总的时间复杂度为O(nlogn),
此外,如果题目中是已排好序的,则可以用首尾两个指针来确定数对。
#include <cstdio>
#include <algorithm>
#include <set>
using namespace std;
int main(){
int k, n;
scanf("%d%d", &k, &n);
set<int> s, res;
int tmp;
for(int i = 0; i < n; i++){
scanf("%d", &tmp);
if(s.count(k-tmp)){
res.insert(min(k-tmp, tmp) );
s.erase(k-tmp);
}
else
s.insert(tmp);
}
set<int>::iterator it = res.begin();
if(it != res.end())
for(; it != res.end(); it++)
printf("%d %d\n", *it, (k-*it));
else
printf("No Solution");
return 0;
}
基准时间限制: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 -1 6 5 3 4 2 9 0 8
Output示例
-1 9 0 8 2 6 3 5
解题思路:
由于这道题是未经过排序的,所以可以用set来保存已存在的数据,插入或者删除的时间复杂度为O(logN),需要对每个点都进行这样的操作,因此总的时间复杂度为O(nlogn),
此外,如果题目中是已排好序的,则可以用首尾两个指针来确定数对。
#include <cstdio>
#include <algorithm>
#include <set>
using namespace std;
int main(){
int k, n;
scanf("%d%d", &k, &n);
set<int> s, res;
int tmp;
for(int i = 0; i < n; i++){
scanf("%d", &tmp);
if(s.count(k-tmp)){
res.insert(min(k-tmp, tmp) );
s.erase(k-tmp);
}
else
s.insert(tmp);
}
set<int>::iterator it = res.begin();
if(it != res.end())
for(; it != res.end(); it++)
printf("%d %d\n", *it, (k-*it));
else
printf("No Solution");
return 0;
}
相关文章推荐
- 3个数和为0
- 51nod 1770 数数字
- 51nod 1459 迷宫游戏
- 51Nod 大数乘法
- 51Nod A^BmodC
- 51Nod 逆序数
- 51NOD 1020 逆序排列
- 51nod 算法马拉松11 A 翻硬币
- 51nod(1264)——线段相交
- 51nod(1183)——dp
- 动态规划初步总结(1)(51Nod,CODE[VS]为例题)
- 51Nod 1086 背包问题 V2(二进制多重背包)
- 51nod 1241 特殊的排序 最少移动次数
- 51nod 可能的路径
- 51nod 1065 最小正子段和(最小正字段和)
- 51nod 1405 树的距离之和 (两次dfs,树形dp)
- 51nod 锁屏密码
- 51nod 1495 中国好区间
- 51nod 1443 路径和树
- Codeforces Round #304 (Div. 2)E. Soldier and Traveling 网络流