难度:4
这道题是离散化的例题,题目里面给的数字是10的9次方范围内的,但是实际上个数只有10的6次方级别甚至更少,所以使用离散化,下面采用了两种方式,一种是map映射,时间是1.6s,然后学习了书上的离散化写法,降到了0.234s,时间复杂度的进步是可观的,
总结一下整数离散化的步骤,首先是把所有数据存在一起,然后排序,然后把数据去重存到新的数组里面,然后就是把老数组里面的数据换成新数组的下标,这一步是用stl里面的二分来实现的,
map代码
#include <bits/stdc++.h>
#define fi first
#define se second
#define pb push_back
#define all(x) (x).begin(), (x).end()
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef pair<int, int> pa;
const int maxn = 200005;
int main() {
int n, m;
cin >> n;
int a[maxn], b[maxn], c[maxn];
int tot[maxn * 3], index = 0;
map<int, int> mp;
for (int i = 0; i < n; i++) {
scanf("%d", &a[i]);
tot[index++] = a[i];
}
cin >> m;
for (int i = 0; i < m; i++) {
scanf("%d", &b[i]);
tot[index++] = b[i];
}
for (int i = 0; i < m; i++) {
scanf("%d", &c[i]);
tot[index++] = c[i];
}
sort(tot, tot + index);
int cnt = 0;
for (int i = 0; i < index; i++) {
if (!i || i && tot[i] != tot[i - 1]) {
mp[tot[i]] = cnt++;
}
}
int num[cnt + 5] = {};
for (int i = 0; i < n; i++) {
num[mp[a[i]]]++;
}
int ans;
int max1 = -1, max2 = -1;
for (int i = 0; i < m; i++) {
if (num[mp[b[i]]] > max1) {
max1 = num[mp[b[i]]];
max2 = num[mp[c[i]]];
ans = i + 1;
} else if (num[mp[b[i]]] == max1 && num[mp[c[i]]] > max2) {
max2 = num[mp[c[i]]];
ans = i + 1;
}
}
cout << ans;
return 0;
}
离散化代码
#include <bits/stdc++.h>
#define fi first
#define se second
#define pb push_back
#define all(x) (x).begin(), (x).end()
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef pair<int, int> pa;
const int maxn = 200005;
int main() {
int n, m;
cin >> n;
int a[maxn], b[maxn], c[maxn];
int tot[maxn * 3], index = 0;
map<int, int> mp;
for (int i = 0; i < n; i++) {
scanf("%d", &a[i]);
tot[index++] = a[i];
}
cin >> m;
for (int i = 0; i < m; i++) {
scanf("%d", &b[i]);
tot[index++] = b[i];
}
for (int i = 0; i < m; i++) {
scanf("%d", &c[i]);
tot[index++] = c[i];
}
sort(tot, tot + index);
int cnt = 0;
int d[maxn * 3];
for (int i = 0; i < index; i++) {
if (!i || i && tot[i] != tot[i - 1]) d[cnt++] = tot[i];
}
for (int i = 0; i < n; i++) {
a[i] = lower_bound(d, d + cnt, a[i]) - d;
}
for (int i = 0; i < m; i++) {
b[i] = lower_bound(d, d + cnt, b[i]) - d;
c[i] = lower_bound(d, d + cnt, c[i]) - d;
}
int num[cnt + 5] = {};
for (int i = 0; i < n; i++) {
num[a[i]]++;
}
int ans;
int max1 = -1, max2 = -1;
for (int i = 0; i < m; i++) {
if (num[b[i]] > max1) {
max1 = num[b[i]];
max2 = num[c[i]];
ans = i + 1;
} else if (num[b[i]] == max1 && num[c[i]] > max2) {
max2 = num[c[i]];
ans = i + 1;
}
}
cout << ans;
return 0;
}