51nod1001 数组中和等于K的数对

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
-1
6
5
3
4
2
9
0
8
Output示例
-1 9
0 8
2 6
3 5

思路:每个元素互不相等,排序以后,线性扫描时二分,用标记去重

代码:

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<vector>
#include<cstring>
#include<cstdlib> 
struct p{
    long long min;
    long long max;
    bool operator <(const p& pp)const{
    return min<pp.min;
    }
};
p res[50005];
int a[50005];
bool f[50005];
using namespace std;
int main(){
    memset(f,false,sizeof(f));
    int n,k;
    cin>>k>>n;
    for(int i=0;i<n;i++){
        cin>>a[i];
    }
    sort(a,a+n);
    int cns=0;
    int slo=0;
    for(int i=0;i<n-1;i++){
        f[i]=true;
        long long  t=k-a[i];
        if(binary_search(a,a+n,t)){
            int index=lower_bound(a,a+n,t)-a;
            if(!f[index]){
                slo++;
                res[cns].max=a[index];
                res[cns].min=a[i];
                cns++;
                    f[index]=true;
            }}  
    }
    if(slo==0){
        cout<<"No Solution"<<endl;
        return 0;
    }
    sort(res,res+cns);
    for(int i=0;i<cns;i++){
        cout<<res[i].min<<" "<<res[i].max<<endl;
    }




    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值