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

给定 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

AC代码:

#include <bits/stdc++.h>
using namespace std;

bool cmp(int a, int b) {
	return a > b;
}

int main() {

	int n;
	cin >> n;
	vector<int> nums;
	for (int i = 0; i < n; i ++ ) {
		int num;
		cin >> num;
		nums.push_back(num);
	}

	unordered_map<int, int> hash;
	vector<int> negatives;
	for (int i = 0; i < n; i ++ ) {
		int negative = abs((i + 1) - nums[i]);
		if (hash.count(negative) == 0) {
			hash.insert({negative, 1});
			negatives.push_back(negative);
		} else {
			hash[negative] ++ ;
		}
	}
	
	sort(negatives.begin(), negatives.end(), cmp);
	
	for (int i = 0; i < negatives.size(); i ++ ) {
		if (hash[negatives[i]] != 1) {
			cout << negatives[i] << " " << hash[negatives[i]] << endl;
		}
	}

	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

老刘莱国瑞

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值