列表

详情


NC24402. [USACO 2013 Mar B]Breed Proximity

描述

Farmer John's N cows (1 <= N <= 50,000) are standing in a line, each described by an integer breed ID. 
Cows of the same breed are at risk for getting into an argument with each-other if they are standing too close. Specifically, two cows of the same breed are said to be "crowded" if their positions within the line differ by no more than K (1 <= K < N). 
 Please compute the maximum breed ID of a pair of crowded cows.

输入描述

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

* Lines 2..1+N: Each line contains the breed ID of a single cow in the
line. All breed IDs are integers in the range 0..1,000,000.

输出描述

* Line 1: The maximum breed ID of a crowded pair of cows, or -1 if
there is no crowded pair of cows.

示例1

输入:

6 3
7
3
4
2
3
4

输出:

4

说明:

INPUT DETAILS:
There are 6 cows standing in a line, with breed IDs 7, 3, 4, 2, 3, and 4.
Two cows of equal breed IDs are considered crowded if their positions
differ by at most 3.

OUTPUT DETAILS:
The pair of cows with breed ID 3 is crowded, as is the pair of cows with
breed ID 4.

原站题解

上次编辑到这里,代码来自缓存 点击恢复默认模板

C++14(g++5.4) 解法, 执行用时: 20ms, 内存消耗: 4712K, 提交时间: 2020-06-03 11:46:32

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int cow[1000005];
int main()
{
    int n,k,ans=0;
    cin>>n>>k;
    memset(cow,0,sizeof(cow));
    for(int i=1;i<=n;i++)
    {
        int t;
        scanf("%d",&t);
        if(i-cow[t]<=k&&t>ans&&cow[t]) ans=t;
        cow[t]=i;
    }
    cout<<ans;
    return 0;
}

Python3(3.5.2) 解法, 执行用时: 207ms, 内存消耗: 13580K, 提交时间: 2020-05-16 21:04:04

N,K=map(int,input().split())
arr=[int(input()) for i in range(N)]
dict_arr=[0 for i in range(1000001)]
maxpz=0
for i in range(N) :
    if i-K-1>=0 :
        dict_arr[arr[i-K-1]]-=1
    if dict_arr[arr[i]]>0 :
        maxpz=max(maxpz,arr[i])
    dict_arr[arr[i]]+=1
print(maxpz)

C++11(clang++ 3.9) 解法, 执行用时: 15ms, 内存消耗: 4344K, 提交时间: 2020-05-19 09:07:59

#include<cstdio>
int n,k,last[1000010],ans=0;
int main()
{
	scanf("%d %d",&n,&k);
	for(int i=1,x;i<=n;i++)
	{
		scanf("%d",&x);
		if(last[x]&&i-last[x]<=k&&x>ans) ans=x;
		last[x]=i;
	}
	printf("%d",ans);
 } 

上一题