题目链接: https://ac.nowcoder.com/acm/problem/20565?&headNav=acm
思路:先排序,然后该种类没入队的入队,如果全部种类没满且前面出现过这个种类,就更新该种类的坐标;如果全部种类满了就求解当前长度。
代码:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
using namespace std;
const int maxn=1e6+5;
const int INF=0x3f3f3f3f;
typedef long long ll;
int n,k;
struct light
{
int x;
int type;
};
light a[maxn];
int vis[100];
int tt[maxn];
bool cmp(light y,light z)
{
return y.x<z.x;
}
int main(){
scanf("%d%d",&n,&k);
int num=0;
int xx;
int cnt=0;
for(int i=1;i<=k;i++)
{
scanf("%d",&num);
for(int j=1;j<=num;j++)
{
scanf("%d",&xx);
a[++cnt].x=xx;
a[cnt].type=i;
}
}
sort(a+1,a+1+n,cmp);
int sum=0;
int ans=INF;
int head=1,tail=1;
while(tail<=n)
{
if(vis[a[tail].type]==0) sum++;
vis[a[tail].type]=a[tail].x;
while(head<=tail&&a[head].x!=vis[a[head].type]) head++;
if(sum==k) ans=min(ans,a[tail].x-a[head].x);
tail++;
}
printf("%d\n",ans);
return 0;
}