题解
[AHOI2018初中组] 分组
1 条题解
-
0
1. 解题思路
按实力升序处理,每个值x优先接到末尾为x-1的最短队伍,没有可接队伍时新建;最终统计所有队伍的最小长度。
**关键规则:**同实力不能加入同队;优先补最短队能避免短队被永远遗留,提高最小队长。
2. 坑点和注意事项
- 数据范围:n≤10^5,|a_i|≤10^9。
- 同实力不能加入同队;优先补最短队能避免短队被永远遗留,提高最小队长。
- map按稀疏负数/大值管理各队尾对应堆,priority_queue动态取最短可接队;普通逐队扫描会退化O(n²),整体改写压缩分组堆会增加算法风险,保留必要map与最小堆(底层vector)。
3. 复杂度
- **时间复杂度:**O(n log n)。
- **空间复杂度:**O(n)。
/* 思路:按实力升序处理,每个值x优先接到末尾为x-1的最短队伍,没有可接队伍时新建;最终统计所有队伍的最小长度。 关键规则:同实力不能加入同队;优先补最短队能避免短队被永远遗留,提高最小队长。 数据范围:n≤10^5,|a_i|≤10^9;注意数组下标和中间运算的数据类型。 时间复杂度:O(n log n);空间复杂度:O(n)。 */ #include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int n; cin >> n; long long a[100005]; // [AHOI2018初中组] 分组:同实力不能加入同队;优先补最短队能避免短队被永远遗留,提高最小队长。 for (int i = 0; i < n; i++) cin >> a[i]; sort(a, a + n); typedef priority_queue<int, vector<int>, greater<int>> Heap; map<long long, Heap> q; for (int i = 0; i < n; i++) { long long x = a[i]; int len = 1; map<long long, Heap>::iterator it = q.find(x - 1); if (it != q.end() && !it->second.empty()) { len = it->second.top() + 1; it->second.pop(); } q[x].push(len); } int ans = n; for (map<long long, Heap>::iterator it = q.begin(); it != q.end(); it++) if (!it->second.empty()) ans = min(ans, it->second.top()); cout << ans << '\n'; }
- 1