P2564 生日礼物

生日礼物

洛谷链接

题目描述:

在一段彩带上有不同颜色的彩珠,求出包含所有颜色彩珠的最短彩带长度。

思路:

我们可以把按彩珠的位置把所有彩珠排一下序,然后从1开始遍历这些彩珠,并记录出现过的颜色数目,知道该数目等于颜色总数,就开始模拟队列的先进先出,不断更新答案。

代码:

 1 #include<cstdio>
 2 #include<iostream>
 3 #include<algorithm>
 4 #define N 1000010
 5 using namespace std;
 6 int r,l,ans,col[N],num,sum,n,m,a;
 7 struct hehe{
 8     int x;
 9     int y;
10 };
11 hehe q[N],que[N];
12 int cmp(hehe a,hehe b){
13     return a.x<b.x;
14 }
15 void join(hehe a){
16     r++;
17     q[r]=a;
18     col[a.y]++;
19     if(col[a.y]==1)
20         num++;
21 }
22 void exit(){
23     col[q[l].y]--;
24     if(!col[q[l].y])
25         num--;
26     l++;
27 }
28 int main(){
29     scanf("%d%d",&n,&m);
30     for(int i=1;i<=m;++i){
31         scanf("%d",&a);
32         for(int j=1;j<=a;++j){
33             sum++;
34             scanf("%d",&que[sum].x);
35             que[sum].y=i;
36         }
37     }
38     sort(que+1,que+n+1,cmp);
39     l=1;r=0;ans=1e9;
40     for(int i=1;i<=n;++i){
41         join(que[i]);
42         while(num==m){
43             ans=min(ans,q[r].x-q[l].x);
44             exit();
45         }
46     }
47     printf("%d",ans);
48     return 0;
49 }
View Code

 

转载于:https://www.cnblogs.com/jsawz/p/6867617.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值