和为给定数

 

在map中访问一个不存在的值,会增加map 的大小

#include<bits/stdc++.h>
#include<map>
using namespace std;
map<int, int> mp; 
int main()
{
	mp[11]=1;
	mp[3]=2;
	mp[4]=3;
	mp[9]=4;
	cout<<mp.size()<<endl;
	cout<<mp[100]<<endl;
	cout<<mp.size()<<endl;
	
}

  

Description

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

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

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

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

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

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

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

Samples
输入数据 1
4
2 5 1 4
6
输出数据 1
1 5
输入数据 2
4
1 2 5 7
4
输出数据 2
2 2
输入数据 3
10
99 36 7 12869 26538 88 127 62 20086 12564
153
输出数据 3
No

 

#include<bits/stdc++.h>
using namespace std;
int n,x,a,ans;
map<int,bool>m;
int main()
{
	cin>>n;
	for(int i=1;i<=n;i++)
		cin>>a,m[a]=1;
	cin>>x;
	for (auto it : m) 
		if(m.count(x-it.first)==1)
		{
			cout<<it.first<<' '<<x-it.first;
			return 0;
		}
	cout<<"No";
	return 0;
}

  

posted @ 2023-11-03 16:29  我微笑不代表我快乐  阅读(9)  评论(0编辑  收藏  举报