洛谷P1102—— A-B數對

1.問題描述:

在這裏插入圖片描述

2.算法分析:

這道題目如果你非要算A - B = C你枚舉都不知道枚舉多少層,我們轉換一下求出A - C = B就可以了,兩個二重循環遍歷,掃一下數組即可,時間複雜度爲O(n^2), 滿分數據爲200000,必吃T,那麼我們來看該怎麼降複雜度呢,可以使用STL 中的map, map的關鍵字存A - C的值,映射的是次數。這樣就可以使得時間複雜度降爲O(logn)可以過得,這也相當於空間換時間了。

3.AC代碼:

#include <cstdio>
#include <algorithm> 
#include <map> 
using namespace std;
const int maxn = 2e5 + 5;
typedef long long LL;

LL a[maxn];
map<LL,LL> mp;

int main() {
	int n;
	LL c;
	scanf("%d%lld", &n, &c);
	for (int i = 1; i <= n; i++) {
		scanf("%lld", &a[i]);
		mp[a[i]]++;
		a[i] -= c;
	}
	LL ans = 0;
	for (int i = 1; i <= n; i++) {
		ans += mp[a[i]];
	}
	printf("%lld\n", ans);
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章