题目概况
题目链接: https://www.luogu.com.cn/problem/P1102
难度: 普及-
题目分析
简化题目: 找出给定数组中有多少对满足A-B=C的数对
涉及知识点: 基础语法、map映射
解题思路:
看似简单,其实呢,很简单。
我们可以学习一位大佬的思路 ,将A-B=C的问题转化为A-C=B
先统计数组中各个元素出现的次数,同时把他们都减C,那么剩下的便是结果B,然后我们再循环一遍,统计B的个数。时间复杂度O(n),妙哉
代码拆解及要点分析
这么简单,拆解这种东西就大可不必了 (就是懒)
完整代码
#include <iostream>
#include <cstdio>
#include <map>
using namespace std;
typedef long long ll;
const int MAXN = 2 * 1e5 + 5;
int n, c;
ll a[MAXN], ans;
map <ll, ll> cnt; //用于统计
int main() {
cin >> n >> c;
for (int i = 1; i <= n; i++) {
cin >> a[i];
}
for (int i = 1; i <= n; i++) {
cnt[a[i]]++;
a[i] -= c;
}
for (int i = 1; i <= n; i++) {
ans += cnt[a[i]];
}
cout << ans << endl;
return 0;
}
本文介绍了洛谷P1102题目的解题过程,该题是一道普及级别的算法问题,涉及基础语法和map映射。解题思路是通过统计数组元素出现次数并减去指定值,找出满足条件的数对,时间复杂度为O(n)。
910

被折叠的 条评论
为什么被折叠?



