試題編號: | 201403-1 |
試題名稱: | 相反數 |
時間限制: | 1.0s |
內存限制: | 256.0MB |
問題描述: |
問題描述 有 N 個非零且各不相同的整數。請你編一個程序求出它們中有多少對相反數(a 和 -a 爲一對相反數)。 輸入格式 第一行包含一個正整數 N。(1 ≤ N ≤ 500)。 輸出格式 只輸出一個整數,即這 N 個數中包含多少對相反數。 樣例輸入 5 樣例輸出 2 |
使用STL庫中set容器:
set關聯容器的一種,是一個排好序的集合,每當插入新元素自動排序;
初始化:set<dataType> T
例如:set<int> s;
insert方法:
s={1,2,3,5}
s.insert{4}
s={1,2,3,4,5}
count(T)方法:
返回s中與T相等的值得個數。
參考代碼:
#include<iostream>
#include <set>
using namespace std;
int main()
{
int n,count,max;
set<int> s;
cin >> n;
count = 0;
while (n--) {
int num;
cin >> num;
s.insert(num);
if (s.count(-num)==1) {
count++;
}
}
cout << count << endl;
return 0;
}