洛谷__P1638 逛画展(双指针)
题目链接:P1638 逛画展 - 洛谷
题目大意:
从m位画家的画作序列中,找长度最短的连续区间[x,y],包含所有画家。
若有多个,输出x最小的。门票价等于区间长度。
代码:
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<vector>
#include<queue>
#include<deque>
#include<stack>
#include<set>
#include<map>
#include<unordered_set>
#include<unordered_map>
#include<bitset>
#include<tuple>
#include<array>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/hash_policy.hpp>
#include <ext/numeric>
#define inf 72340172838076673
#define int long long
#define endl '\n'
#define F first
#define S second
#define mst(a,x) memset(a,x,sizeof (a))
#define pb push_back
#define gmap __gnu_pbds::gp_hash_table
#define power __gnu_cxx::power
using namespace std;
typedef pair<int, int> pii;
const int N = 1000086, mod = 998244353;
int n, m;
int a[N];
gmap<int, int> mp;
void solve() {
cin >> n >> m;
for (int i = 1; i <= n; i++) {
cin >> a[i];
}
int cnt = 0, mn = inf;
int x = 0, y = 0;
for (int l = 1, r = 1; r <= n; r++) {
mp[a[r]]++;
if (mp[a[r]] == 1) cnt++;
while (cnt == m) {
if (mn > r - l) {
x = l, y = r;
mn = r - l;
}
mp[a[l]]--;
if (mp[a[l++]] == 0) cnt--;
}
}
cout << x << " " << y << endl;
}
signed main() {
ios::sync_with_stdio(false);
cin.tie(nullptr), cout.tie(nullptr);
int T = 1;
// cin >> T;
while (T--) solve();
return 0;
}

浙公网安备 33010602011771号