和为给定数

给出若干个整数,询问其中是否有一对数的和等于给定的数。 这样的一对数下标可以相等。

Format
Input
第一行是整数n(0 < n ≤ 100,000),表示有n个整数。

第二行是n个整数。整数的范围是在0到10^8之间。

第三行是一个整数m(0≤m≤2^30),表示需要得到的和。 .

Output
若存在和为m的数对,输出两个整数,小的在前,大的在后,中间用单个空格隔开。

若有多个数对满足条件,选择数对中较小的数更小的。

若找不到符合要求的数对,输出一行No。

#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 7;
int a[N];
map<int, bool>f;
int n, m, ans;
int main() {
    scanf("%d", &n);
    for (int i = 1; i <= n; i++)
        scanf("%d", &a[i]);
    sort(a + 1, a + n + 1);
    scanf("%d", &m);
    for (int i = 1; i <= n; i++)
        f[a[i]] = true;

    for (int i = 1; i <= n; i++) 
        if (f[m-a[i]] == true) 
		{
            cout << a[i] << " " << m - a[i];
            return 0;
        }
    puts("No");
    return 0;
}

  

#include<bits/stdc++.h>
using namespace std;
map<int,bool> v;
int n,m,x;
int main(){
	cin>>n;
	for(int i=1; i<=n; i++){
		cin>>x;
		v[x]=true;
	}
	cin>>m;
	for(auto i=v.begin(); i!=v.end(); i++)
	{
		if(v.find(m-(*i).first)!=v.end())
//这里要查找下,不然当找一个不存在的元素时,map中会加入新元素,迭代器会混乱的。 { cout<<(*i).first<<" "<<m-(*i).first; return 0; } } cout<<"No"; return 0; }

  下面这个程序就是错的

#include<bits/stdc++.h>
using namespace std;
map<int,bool> v;
int n,m,x;
int main(){
	cin>>n;
	for(int i=1; i<=n; i++){
		cin>>x;
		v[x]=true;
	}
	cin>>m;
	for(auto i=v.begin(); i!=v.end(); i++){
		if(v[m-(*i).first]){
			cout<<(*i).first<<" "<<m-(*i).first;
			return 0;
		}
	}
	cout<<"No";
	return 0;
}

  

原文地址:https://www.cnblogs.com/cutemush/p/15618747.html