hrbust 1721 A + B = 0 map的应用
13级春季校赛的热身题,但优化后我的代码也超时了,后来看了看学长的解法,觉得最简单的还是map,再一次感受到了map的强大。
题目描述如下
Description |
There is an integer set A. How many couples of a and b, which can make a+b=0(a∈A, b∈A,a<=b). |
Input |
There are multiple test cases. The first line is an integer T indicating for the number of test cases. The first line of each case is an integer n, standing for the number of integers in set A. The second line is n integers in set A separated by space. (1<=n<=100 000,|ai|<=1000 000 000) |
Output |
For each test case, output all the unique couples of a and b by the order of a from small to large. If there is no such a situation, output "<empty>". Output a blank line after each case. |
Sample Input |
2 6 -1 0 1 4 -1 -4 3 1 1 2 |
Sample Output |
-4 4 -1 1 <empty> |
map的遍历方式:使用迭代器,it->first指原集合的元素,it-second指映射集合的元素。这样仅用O(N)的复杂度就求出了答案,尽管map是c++封装好的函数,运行相对较慢。
对比数组来说,map的好处有很好的处理负值,能够容下更大的数字等等,代码如下:
#include<cstdio>
#include<map>
#include<cstring>
#include<iostream>
using namespace std;
int main()
{
int n,t,b,mark;
scanf("%d",&t);
while(t--)
{
map<int,int>a;
a.clear();
mark = ;
scanf("%d",&n);
while(n--)
{
scanf("%d",&b);
a[b]++;
}
map<int,int>::iterator it;
for(it = a.begin(); it->first < && it != a.end(); it++)
{
///cout<<"first = "<<it->first<<endl;
if(it->second)
{
///cout<<"second = "<<it->second<<endl;
if(a[-it->first])
{
printf("%d %d\n",it->first,-it->first);
mark = ;
}
}
}
if(a[] >= )
{
cout<<"0 0"<<endl;
mark = ;
}
if(mark == )
printf("<empty>\n");
printf("\n");
}
}
最新文章
- 如何访问wikipedia 的中文版
- 【转载】javascript与C#的语法区别
- YCSB测试Mysql,MongoDB,TokuMX,Couchbase性能
- 记一次PHP7+opcache+zmq出现SIGSEGV 问题的查找(一次不成功的bug查找)
- PCTUSED和PCTFREE对数据操作的影响
- 安装Win7或者XP系统用虚拟光驱加载Win7或者XP镜像 iso文件xp win7wim文件
- throw 语句
- CALayer的分析
- POJ 1777 mason素数
- maven ArtifactTransferException: Failure to transfer
- 实验一:点亮led
- Intent 意图 结构 简介
- /usr/lib64/libstdc++.so.6: version `GLIBCXX_3.4.15&#39; not found,解压rpm包
- Android定调的发展
- python py_innodb_page_info.py -v /usr/local/var/mysql/ibdata1
- linux 下 Emacs dired 模式 隐藏 dot file ";.filename"; 文件
- Java项目中启动Tomcat报错invalid LOC header
- 【转】学习Robot Framework必须掌握的库—-BuiltIn库
- python制作模块
- Two strings 的另一种解法
热门文章
- OutputDebugString输出调试信息到debugtrack
- mysql读写分离配置,利用mybatis实现,解释为什么dynamicDataSource不行
- js算数方法
- hdu_3562_B-number(记忆化搜索|数位DP)
- malloc without free, what happens?
- Linux设置静态IP【转】
- MFC下对串口的操作以及定时器的调用
- linux git升级到1.8.3
- find tar 压缩第一层目录,用于资料备份。
- 12C cdb/pdb 配置监听