题目:
|
|
思路:
这里就是暴力模拟一遍,不同的是,要用 umap 来模拟每只青蛙跳跃在 n 范围内
所以我一开始一直用 vector 和 数组 啥的,一直 TLE 不知道为啥 (;´༎ຶД༎ຶ`)
然后找到对应的 坐标累加有多少只青蛙跳到这,然后取出 最多青蛙在同一坐标数量,就是我们捕获到的最多青蛙
代码详解如下:
#include <iostream>
#include <unordered_map>
#define endl '\n'
#define x first
#define y second
#define umap unordered_map
#define ___G std::ios::sync_with_stdio(false),cin.tie(0), cout.tie(0)
using namespace std;
inline void solve()
{
int n = 0;
umap<int, int>a; // a 数组为我们青蛙跳跃的记录
umap<int, int>r; // r 为各个点的坐标,我们青蛙跳到这个坐标总共有多少只
cin >> n;
for (int i = 0, x; i < n; ++i)
{
cin >> x;
if (x > n)
{
// 如果一开始就跳跃超出范围了
// 我们就不遍历这一只青蛙
continue;
}
// 这里是 以 map 中 x 为 青蛙跳跃长度 y 为青蛙数量
// 用 umap 不用 vector 是因为用 vector 的话还要 PII
// 而我们 用 umap 效率高,查询速度是 O(1) 方便省去了定义 PII
// 还要注意这里为什么要用 ++ 是因为 万一有跳跃长度相同的青蛙呢
a[x]++;
}
int ans = 0; // ans 为我们答案捕获青蛙的数量
// 开始模拟跳跃
for (auto &i : a)
{
// now 为我们青蛙现在跳跃到的坐标
int now = i.x;
// 如果跳跃后所在的坐标在范围内
// 我们开始统计该坐标到达的数量
while (now <= n)
{
// r 开始记录到这个坐标的青蛙总和
r[now] += i.y;
// 查找所有坐标中数量最多的青蛙,就是我们得到最多的青蛙
if (ans < r[now])
ans = r[now];
// 开始跳跃
now += i.x;
}
}
cout << ans << endl;
return;
}
int main()
{
___G;
int _t;
cin >> _t;
while (_t--)
{
solve();
}
return 0;
}
最后提交: