B. Uniqueness 删除最小区间内的元素使得剩余元素唯一
B. Uniqueness
2 seconds
256 megabytes
standard input
standard output
You are given an array a1,a2,…,ana1,a2,…,an. You can remove at most one subsegment from it. The remaining elements should be pairwise distinct.
In other words, at most one time you can choose two integers ll and rr (1≤l≤r≤n1≤l≤r≤n) and delete integers al,al+1,…,aral,al+1,…,ar from the array. Remaining elements should be pairwise distinct.
Find the minimum size of the subsegment you need to remove to make all remaining elements distinct.
The first line of the input contains a single integer nn (1≤n≤20001≤n≤2000) — the number of elements in the given array.
The next line contains nn spaced integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109) — the elements of the array.
Print a single integer — the minimum size of the subsegment you need to remove to make all elements of the array pairwise distinct. If no subsegment needs to be removed, print 00.
3
1 2 3
0
4
1 1 2 2
2
5
1 4 1 4 9
2
In the first example all the elements are already distinct, therefore no subsegment needs to be removed.
In the second example you can remove the subsegment from index 22 to 33.
In the third example you can remove the subsegments from index 11 to 22, or from index 22 to 33, or from index 33 to 44.
题意:删除一段连续的区间,使得剩下的所有元素都是唯一的,求满足要求的最小区间长度
题解:逆向考虑,从左边开始[1,i ]最多可以取x个不同的数,然后从n到 i+1 最多可以连续取y个不同的数,不断枚举 i ,取cnt=max( cnt,x+y) 的最大值,n - cnt就是可以删除的最小长度
#include<iostream>
#include<algorithm>
#include<math.h>
#include<map>
using namespace std;
int a[];
map<int,int>mp;
int main()
{
int n,ans=;
cin>>n;
for(int i=;i<=n;i++)
cin>>a[i];
for(int i=;i<=n;i++)
{
mp.clear();
int cnt=;
for(int j=;j<=i;j++)
{
if(mp[a[j]]==)
{
mp[a[j]]=;
cnt++;
}
else
break;
} for(int j=n;j>i;j--)
{
if(mp[a[j]]==)
{
mp[a[j]]=;
cnt++;
}
else
break;
}
ans=max(ans,cnt);
}
cout<<n-ans<<endl;
return ;
}
最新文章
- ADO.NET--收藏整理别人的教程
- [UML]UML系列——类图class的泛化关系
- 【荐1】Total Commander 7.57 个人使用设置 及 常用快捷键 备忘
- 基于CWMP(TR069)协议ACS服务器的搭建
- BFC引发的关于position的思考
- Eclipse错误
- 第一个androidAPP项目总结—ListView的上拉和下拉
- java读取网页
- poj1159 dp(滚动数组优化)
- Openjudge-NOI题库-二维数组回形遍历
- manacher算法,求回文串
- 初学Java Web(5)——cookie-session学习
- win10远程桌面出现身份验证错误。要求的函数不受支持
- android to hide the keybord
- lua luv分析
- Hessian---java远程通讯 (zhuan)
- Binomial Coefficient(二项式系数)
- python Requests库网络爬取IP地址归属地的自动查询
- HDFS概要
- js中window.location.search的用法和作用。