题目描述
Farmer John‘s N cows (1 <= N <= 100,000) are lined up in a row. Each cow is identified by an integer "breed ID" in the range 0...1,000,000,000; the breed ID of the ith cow in the lineup is B(i). Multiple cows can share the same breed ID.
FJ thinks that his line of cows will look much more impressive if there is a large contiguous block of cows that all have the same breed ID. In order to create such a block, FJ chooses up to K breed IDs and removes from his lineup all the cows having those IDs. Please help FJ figure out the length of the largest consecutive block of cows with the same breed ID that he can create by doing this.
农夫约翰的N(1 <= N <= 100,000)只奶牛排成了一队,每只牛都用编上了一个“血统编号”,该编号为范围0...1,000,000,000的整数。血统相同的奶牛有相同的编号,也就是可能有多头奶牛是相同的"血统编号"。
约翰觉得如果连续排列的一段奶牛有相同的血统编号的话,奶牛们看起来会更具有威猛。为了创造这样的连续段,约翰最多能选出k种血统的奶牛,并把他们全部从队列中赶走。
请帮助约翰计算这样做能得到的由相同血统编号的牛构成的连续段的长度最大是多少?
输入输出格式
输入格式:
* Line 1: Two space-separated integers: N and K.
* Lines 2..1+N: Line i+1 contains the breed ID B(i).
输出格式:
* Line 1: The largest size of a contiguous block of cows with
identical breed IDs that FJ can create.
输入输出样例
输入样例#1:
9 1 2 7 3 7 7 3 7 5 7
输出样例#1:
4
说明
There are 9 cows in the lineup, with breed IDs 2, 7, 3, 7, 7, 3, 7, 5, 7. FJ would like to remove up to 1 breed ID from this lineup.
By removing all cows with breed ID 3, the lineup reduces to 2, 7, 7, 7, 7, 5, 7. In this new lineup, there is a contiguous block of 4 cows with the same breed ID (7).
我们发现,如果一个区间的颜色数量小于等于$K + 1$的话,那么这一段区间的最大答案就是出现次数最多的数。
显然最左的、合法的l随着r的增加而不减。
所以直接区间扫过去就行了。
#include <iostream> #include <cstdio> #include <algorithm> #include <cstring> #include <queue> #include <algorithm> #include <map> using namespace std; #define reg register #define gc getchar inline int read() { int res=0;char ch=gc();bool fu=0; while(!isdigit(ch)){if(ch==‘-‘)fu=1;ch=gc();} while(isdigit(ch))res=(res<<3)+(res<<1)+(ch^48), ch=gc(); return fu?-res:res; } map <int, int> mp; int tot; int n, k; int a[100005]; int ans; int cnt[100005]; int main() { n = read(), k = read(); for (reg int i = 1 ; i <= n ; i ++) { a[i] = read(); if (!mp[a[i]]) mp[a[i]] = ++tot; a[i] = mp[a[i]]; } int l = 1, r = 0; int num = 0; while(r <= n) { r ++; if (!cnt[a[r]]) num++; cnt[a[r]] ++; if (num >= k + 2) { while(l <= r and num >= k + 2) { if (cnt[a[l]] == 1) num--; cnt[a[l]]--; l++; } } ans = max(ans, cnt[a[r]]); } cout << ans << endl; return 0; }
原文地址:https://www.cnblogs.com/BriMon/p/9784418.html