zoukankan      html  css  js  c++  java
  • 和为给定数

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

    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;
    }
    

      

  • 相关阅读:
    【C++】深度探索C++对象模型读书笔记--关于对象(Object Lessons)
    【操作系统】调度算法
    【vim】vim常用命令
    【linux】linux的数据流重定向
    以太网帧,IP,TCP,UDP首部结构
    IPv4编址及子网划分
    【计算机网络】计算机网络模型
    【计算机网络】NAT:网络地址转换
    【设计模式】C++中的单例模式
    (转)linux查找技巧: find grep xargs
  • 原文地址:https://www.cnblogs.com/cutemush/p/15618747.html
Copyright © 2011-2022 走看看