九度OJ - 1352 - 和为S的两个数字

题目描述

输入一个递增排序的数组和一个数字S,在数组中查找两个数,是的他们的和正好是S,如果有多对数字的和等于S,输出两个数的乘积最小的。

输入

每个测试案例包括两行:
第一行包含一个整数n和k,n表示数组中的元素个数,k表示两数之和。其中1 <= n <= 10^6,k为int
第二行包含n个整数,每个数组均为int类型。

输出

对应每个测试案例,输出两个数,小的先输出。如果找不到,则输出“-1 -1”

样例输入

6 15
1 2 4 7 11 15

样例输出

4 11


#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;

int num[1000005];

int main()
{
    int n, k;
    while(scanf("%d %d", &n, &k)!=EOF){
        for(int i = 0; i < n; i++)  
            scanf("%d", &num[i]);

        if(k < 0){
            cout << "-1 -1" << endl;
            continue;
        }

        int start = 0, end = n-1;

        while(end > start && num[start]+num[end] != k){
            if(num[start]+num[end] > k)
                end--;
            else
                start++;
        }

        if(end <= start)
            cout << "-1 -1" << endl;
        else
            cout << num[start] << " " << num[end] << endl;
    }
    return 0;
}

你可能感兴趣的:(九度OJ)