[SCOI2009]生日礼物
题目地址:
基本思路:
比较容易想到尺取,我们先将每个珠子对应到它的颜色,用结构体做一个类似离散化的排序处理,
然后我们尺取,每次使用来维护,尺取到包含所有颜色的区间,
然后算出这些区间的区间长度,对所有区间的长度取一个最小值作为答案就好了。
参考代码:
#pragma GCC optimize(2)
#pragma GCC optimize(3)
#include <bits/stdc++.h>
using namespace std;
#define IO std::ios::sync_with_stdio(false); cin.tie(0)
#define int long long
#define SZ(x) ((int)(x).size())
#define all(x) (x).begin(), (x).end()
#define rep(i, l, r) for (int i = l; i <= r; i++)
#define per(i, l, r) for (int i = l; i >= r; i--)
#define mset(s, _) memset(s, _, sizeof(s))
#define pb push_back
#define pii pair <int, int>
#define mp(a, b) make_pair(a, b)
#define INF 0x3f3f3f3f
inline int read() {
int x = 0, neg = 1; char op = getchar();
while (!isdigit(op)) { if (op == '-') neg = -1; op = getchar(); }
while (isdigit(op)) { x = 10 * x + op - '0'; op = getchar(); }
return neg * x;
}
inline void print(int x) {
if (x < 0) { putchar('-'); x = -x; }
if (x >= 10) print(x / 10);
putchar(x % 10 + '0');
}
struct Node{
int color,pos;
bool operator < (const Node &no) const{
return pos < no.pos;
}
};
vector<Node> vec;
map<int,int> memo;
int n,k;
signed main() {
IO;
n = read(),k = read();
rep(i,1,k) {
int t = read();
rep(j, 1, t) {
int x = read();
vec.push_back({i, x});
}
}
sort(all(vec));
int r = 0,ans = INF;
memo[vec[0].color]++;
for(int l = 0 ; l < SZ(vec) ; l++) {
while (r + 1 < SZ(vec) && memo.size() < k) {
memo[vec[++r].color]++;
if (memo.size() == k) break;
}
if (memo.size() == k) ans = min(ans, vec[r].pos - vec[l].pos);
memo[vec[l].color]--;
if(memo[vec[l].color] == 0) memo.erase(vec[l].color);
}
cout << ans << '\n';
return 0;
}
京公网安备 11010502036488号