• USACO Cow Lineup


    USACO Cow Lineup

    洛谷传送门

    JDOJ传送门

    Description

    Problem 1: Cow Lineup [Brian Dean and Daniel Dara, 2012]

    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.

    Input

    * Line 1: Two space-separated integers: N and K.

    * Lines 2..1+N: Line i+1 contains the breed ID B(i).

    Output

    * Line 1: The largest size of a contiguous block of cows with
    identical breed IDs that FJ can create.

    Sample Input

    9 1 2 7 3 7 7 3 7 5 7

    Sample Output

    4


    题解:

    允许删K种,最后还必须连续,那么想到滑动窗口。也就是,采用滑动窗口的模式遍历所有包含种类数小于等于K+1的区间们。为什么是K+1呢,因为最多删除K种还剩一种。然后每次合法区间的最多种类来更新答案。

    离散化开桶已经是套路的东西了,不需要说了。

    然后我们思考如何快速找出每个合法区间的最多种类。

    我们发现只需要拿cow[a[r]]来更新答案就行了。因为每次右移较之上次移动都只会有最右侧的节点+。那么每次更新也就是最右侧节点。

    代码:

    #include<iostream>
    #include<cstdio>
    #include<algorithm>
    #include<cstring>
    #include<map>
    using namespace std;
    const int maxn = 100010;
    int n,k,cow[maxn],a[maxn];
    int cnt;
    map<int,int> mp;
    int getid(int num)
    {
    	if(!mp[num])mp[num]=++cnt;
    	return mp[num];
    }
    int main()
    {
    	cin>>n>>k;
    	int t;
    	for(int i=1;i<=n;i++)
    	{
    		cin>>t;
    		a[i]=getid(t);
    	}
    	int ans=1;
    	int l=1,r=0,typ=0;
    	while(r<=n)
    	{
    		r++;
    		if(cow[a[r]]==0)
    			typ++; 
    		cow[a[r]]++;
    		while(typ>k+1)
    		{
    			cow[a[l]]--;
    			if(cow[a[l]]==0)
    				typ--;
    			l++;
    		}
    		ans=max(ans,cow[a[r]]); 
    	}
    	cout<<ans<<endl;
    	return 0;
    }
    
  • 相关阅读:
    记一次css载入指定url失败
    更改MySQL密码后Navicat连接失败错误代码1045
    Maven项目中不显示Maven Dependenciesy依赖
    Mysql导入sql文件报错1064
    nexus-3.2.0-01.zip安装以及如何启动服务
    JS中函数的词法作用域
    关于JS中函数的返回值的一点死思考
    swich语句的小练习
    sublime的小技巧
    RPC failed; curl 18 transfer closed with outstanding read data remaining
  • 原文地址:https://www.cnblogs.com/fusiwei/p/14031747.html
Copyright © 2020-2023  润新知