列表

详情


NC24127. [USACO 2011 Nov S]Cow Lineup

描述

Farmer John has hired a professional photographer to take a picture of some of his cows.  Since FJ's cows represent a variety of different breeds, he would like the photo to contain at least one cow from each distinct breed present in his herd.
FJ's N cows are all standing at various positions along a line, each described by an integer position (i.e., its x coordinate) as well as an integer breed ID.  FJ plans to take a photograph of a contiguous range of cows along the line.  The cost of this photograph is equal its size -- that is, the difference between the maximum and minimum x coordinates of the cows in the range of the photograph. 
Please help FJ by computing the minimum cost of a photograph in which there is at least one cow of each distinct breed appearing in FJ's herd.

输入描述

* Line 1: The number of cows, N (1 <= N <= 50,000).
* Lines 2..1+N: Each line contains two space-separated positive integers specifying the x coordinate and breed ID of a single cow. Both numbers are at most 1 billion.

输出描述

* Line 1: The smallest cost of a photograph containing each distinct breed ID.

示例1

输入:

6
25 7
26 1
15 1
22 3
20 1
30 1

输出:

4

说明:

There are 6 cows, at positions 25,26,15,22,20,30, with respective breed IDs
7,1,1,3,1,1.
The range from x=22 up through x=26 (of total size 4) contains each of the
distinct breed IDs 1, 3, and 7 represented in FJ's herd.

原站题解

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

C++14(g++5.4) 解法, 执行用时: 27ms, 内存消耗: 1664K, 提交时间: 2020-10-20 11:07:49

#include <stdio.h>
#include <algorithm>
using namespace std;
struct node
{
	int pos,id;
	bool operator<(const node &a)const
	{
		return pos<a.pos;
	}
}a[500010],q[500010];
int b[500010],c[500010];
int vis[500010];
int main()
{
	int n;
	scanf("%d",&n);
	for(int i=1;i<=n;i++)
	{
		scanf("%d%d",&a[i].pos,&a[i].id);
	}
	sort(a+1,a+1+n);
	for(int i=1;i<=n;i++)b[i]=a[i].pos,c[i]=a[i].id;
	sort(c+1,c+1+n);
	int len2=unique(c+1,c+1+n)-c-1;
	int l=1,r=0,ans=1e9;
	int cnt=0;
	for(int i=1;i<=n;i++)
	{
		int id=lower_bound(c+1,c+1+len2,a[i].id)-c;
		vis[id]++;
		q[++r].pos=a[i].pos;q[r].id=id;
		if(vis[id]==1)cnt++;
		while(l<=r&&vis[q[l].id]>1)vis[q[l].id]--,l++;
		if(cnt==len2)ans=min(ans,a[i].pos-q[l].pos);
	}
	printf("%d\n",ans);
}

C++11(clang++ 3.9) 解法, 执行用时: 30ms, 内存消耗: 2052K, 提交时间: 2020-10-19 20:46:11

#include<bits/stdc++.h>
#define LL long long
using namespace std;
const int N=5e4+5,inf=2e9;
struct node{int x,y;}a[N];
int n,b[N],len,ans=inf,cnt[N];
bool cmp(node a,node b){return a.x<b.x;}
int main(){
	scanf("%d",&n);
	for(int i=1;i<=n;i++)scanf("%d%d",&a[i].x,&a[i].y),b[++len]=a[i].y;
	sort(b+1,b+len+1);len=unique(b+1,b+len+1)-b-1;
	for(int i=1;i<=n;i++)a[i].y=lower_bound(b+1,b+len+1,a[i].y)-b;
	sort(a+1,a+n+1,cmp);
	for(int i=1,l=1,now=0;i<=n;i++){
		cnt[a[i].y]++;if(cnt[a[i].y]==1)now++;
		while(now==len&&cnt[a[l].y]>1)cnt[a[l].y]--,l++;
		if(now==len)ans=min(ans,a[i].x-a[l].x);
	}
	printf("%d\n",ans);
	return 0;
}

上一题