PAT 乙级 1083 是否存在相等的差

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/a845717607/article/details/86413670

1083 是否存在相等的差 (20 point(s))

给定 N 张卡片,正面分别写上 1、2、……、N,然后全部翻面,洗牌,在背面分别写上 1、2、……、N。将每张牌的正反两面数字相减(大减小),得到 N 个非负差值,其中是否存在相等的差?

输入格式:

输入第一行给出一个正整数 N(2 ≤ N ≤ 10 000),随后一行给出 1 到 N 的一个洗牌后的排列,第 i 个数表示正面写了 i 的那张卡片背面的数字。

输出格式:

按照“差值 重复次数”的格式从大到小输出重复的差值及其重复的次数,每行输出一个结果。

输入样例:

8
3 5 8 6 2 1 4 7

输出样例:

5 2
3 3
2 2

经验总结:

这一题也很简单啦,使用map自动排序的特性逆向输出,可以很方便的解决问题~(๑>ڡ<)☆

AC代码 

#include <cstdio>
#include <map>
using namespace std;
int main()
{
	int n,t;
	map<int,int> mp;
	while(~scanf("%d",&n))
	{
		for(int i=1;i<=n;++i)
		{
			scanf("%d",&t);
			int temp=t-i>0?t-i:i-t;
			if(mp.count(temp)==0)
				mp[temp]=1;
			else
				++mp[temp];
		}
		for(map<int,int>::reverse_iterator it=mp.rbegin();it!=mp.rend();++it)
		{
			if(it->second>1)
				printf("%d %d\n",it->first,it->second);
		}
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/a845717607/article/details/86413670