zoukankan      html  css  js  c++  java
  • 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;
    }
    
  • 相关阅读:
    网址收藏
    Linux创建swap文件
    vim命令大全
    char * 和字符数组
    JSR 203终于要出来啦
    对象关系技术的探讨
    最近编码更流畅了
    孤独终止的地方,就是广场开始的地方......
    不要奢望.NET能够跨平台
    实现了HTTP多线程下载
  • 原文地址:https://www.cnblogs.com/fusiwei/p/14031747.html
Copyright © 2011-2022 走看看