牛客上遇到一个问题,可以用尺取+离散化做,但是尺取本质上也是双指针算法,所以复习一下双指针算法
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.
Line 1: Two space-separated integers: N and K.
Lines 2…1+N: Line i+1 contains the breed ID B(i).
输入
9 1
2
7
3
7
7
3
7
5
7
输出
4
INPUT DETAILS:
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.
OUTPUT DETAILS:
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).
AC代码
#include
using namespace std;
map<long long,int> vis;
int a=0,r=0,l=1,x[100005],ans=0;
int main(){
int n,k;
cin>>n>>k;
for(int i=1;i<=n;i++){
cin>>x[i];
}
while(r<=n){
r++;
if(!vis[x[r]]){
a++;
}
vis[x[r]]++;
while(a==k+2){
vis[x[l]]--;
if(!vis[x[l]]){
a--;
}
l++;
}
ans=max(ans,vis[x[r]]);
}
cout<<ans;
return 0;
}
题意是给定一段序列,
Acwing上两题作为练习:
给定一个长度为n的整数序列,请找出最长的不包含重复数字的连续区间,输出它的长度。
第一行包含整数n。
第二行包含n个整数(均在0~100000范围内),表示整数序列。
共一行,包含一个整数,表示最长的不包含重复数字的连续子序列的长度。
1≤n≤100000
5
1 2 2 3 5
3
#include
using namespace std;
#define INF 0x3f3f3f3f
const int maxn=1e5+10;
int a[maxn],s[maxn],n,ans=1;
int main(){
scanf("%d",&n);
for(int i=1;i<=n;i++){
scanf("%d",&a[i]);
}
for(int i=1,j=1;i<=n;i++){
s[a[i]]++;
while(j<i&&s[a[i]]>1){
s[a[j]]--;
j++;
}
int t=i-j+1;
ans=max(ans,t);
}
printf("%d",ans);
return 0;
}
今日感悟:
搞清楚算法,做相关题以后,明天要留出来时间做比赛题,比赛的时候是不知道用什么算法的.