20210118CF训练之A题A. Spyke Talks——STL库中map搜索的初应用

24 篇文章 0 订阅
24 篇文章 0 订阅

Polycarpus is the director of a large corporation. There are n secretaries working for the corporation, each of them corresponds via the famous Spyke VoIP system during the day. We know that when two people call each other via Spyke, the Spyke network assigns a unique ID to this call, a positive integer session number.

One day Polycarpus wondered which secretaries are talking via the Spyke and which are not. For each secretary, he wrote out either the session number of his call or a 0 if this secretary wasn’t talking via Spyke at that moment.

Help Polycarpus analyze these data and find out the number of pairs of secretaries that are talking. If Polycarpus has made a mistake in the data and the described situation could not have taken place, say so.

Note that the secretaries can correspond via Spyke not only with each other, but also with the people from other places. Also, Spyke conferences aren’t permitted — that is, one call connects exactly two people.

Input
The first line contains integer n (1 ≤ n ≤ 103) — the number of secretaries in Polycarpus’s corporation. The next line contains n space-separated integers: id1, id2, …, idn (0 ≤ idi ≤ 109). Number idi equals the number of the call session of the i-th secretary, if the secretary is talking via Spyke, or zero otherwise.

Consider the secretaries indexed from 1 to n in some way.

Output
Print a single integer — the number of pairs of chatting secretaries, or -1 if Polycarpus’s got a mistake in his records and the described situation could not have taken place.

Examples
Input
6
0 1 7 1 7 10
Output
2
Input
3
1 1 1
Output
-1
Input
1
0
Output
0
Note
In the first test sample there are two Spyke calls between secretaries: secretary 2 and secretary 4, secretary 3 and secretary 5.

In the second test sample the described situation is impossible as conferences aren’t allowed.

题意:很简单,就是要你帮助记录秘书用"啥啥啥"通话的次数;当然不存在3个人一起同一通电话。
这个想要用常规方法去做肯定是可以的,但是比较麻烦;
这里建议可以使用STL中的map容器储存并搜索。
又快又简单。
代码:

#include<bits/stdc++.h>
#include<map>//map搜索的初应用 
#define LL long long
using namespace std;
int main()
{
	LL n;
	cin>>n;
	map<int,int> id;
	for(LL i=0;i<n;i++){
		LL mp;
		cin>>mp;
		if(id.find(mp)==id.end()) id[mp]=1;//用map容器储存:边搜索记录边输入,不用定义空间。 
		else id[mp]++;
	}
	LL count=0,flag=0;
	for(map<int,int>::iterator it = id.begin();it!=id.end();it++){//迭代器:搜索数目一样的数并实时记录 
		if(it->first==0) continue;
		if(it->second>2){
			flag=1;
			break;
		}
		if(it->second==2) count++;
	}
	if(flag==1) cout<<"-1"<<endl;
	else if(count) cout<<count<<endl;
	else cout<<"0"<<endl; 
    return 0;
}

第一次用STL中的map,还是模仿着写的,其中很多东西还没有记住,希望在日后可以健全我的STL库。——感想

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值