小熊的果篮(fruit)【CSPJ2021】

题目描述

小熊的水果店里摆放着一排 n 个水果。每个水果只可能是苹果或桔子,从左到右依次用正整数 1、2、3、……、n 编号。连续排在一起的同一种水果称为一个“块”。小熊要把这一排水果挑到若干个果篮里,具体方法是:每次都把每一个“块”中最左边的水果同时挑出,组成一个果篮。重复这一操作,直至水果用完。注意,每次挑完一个果篮后,“块”可能会发生变化。比如两个苹果“块”之间的唯一桔子被挑走后,两个苹果“块”就变成了一个“块”。请帮小熊计算每个果篮里包含的水果。、

输入输出格式

输入格式:

输入的第一行包含一个正整数 n,表示水果的数量。
输入的第二行包含 n 个空格分隔的整数,其中第 i 个数表示编号为 i 的水果的种类,1 代表苹果,0 代表桔子。

输出格式:

输出若干行。
第 i 行表示第 i 次挑出的水果组成的果篮。从小到大排序输出该果篮中所有水果的编号,每两个编号之间用一个空格分隔。

输入输出样例

输入样例#1:

输入样例1:
12
1 1 0 0 1 1 1 0 1 1 0 0
输入样例2:
20
1 1 1 1 0 0 0 1 1 1 0 0 1 0 1 1 0 0 0 0

输出样例#1:

输出样例1:
1 3 5 8 9 11
2 4 6 12
7
10
输出样例2:
1 5 8 11 13 14 15 17
2 6 9 12 16 18
3 7 10 19
4 20

提示信息

对于 100% 的数据,n ≤ 2 × 10^5。

题目分析

这道题没有算法,不,是模拟算法,根据题目的意思做:

1.定义一个“块”:

用结构体来做更好:

struct kuai
{
	int st;
	int ed;
	int val;
};

2.存入块中:

    cin>>n;
	for(int i=1;i<=n;i++) cin>>d[i];
	if(d[n]==0) d[n+1]=1;
	else d[n+1]=0;
	for(int i=2;i<=n+1;i++)
	{
		if(d[i]!=d[i-1]) 
		{
			q.push((kuai){tempst,i-1,d[i-1]});
			tempst=i;
		}
	}

3.取每个块最左边的水果:

从原块开始处往右走,遇到没有标记的就取,然后标记

        while(!q.empty())
		{
			kuai temp=q.front();
			q.pop();
			while(vis[temp.st]&&temp.st<=temp.ed) temp.st++;
			if(temp.st>temp.ed) continue;
			cout<<temp.st<<" ";
			cnt--;
			vis[temp.st]=1;
			if(temp.ed==temp.st) continue;
			temp.st++;
			q2.push(temp);
		}

4.合并相邻两“块”:

        while(!q2.empty())
		{
			kuai temp=q2.front();
			q2.pop();
			while(!q2.empty())
			{
				kuai temp2=q2.front();
				if(temp2.val==temp.val)//同一种水果
				{
					temp.ed=temp2.ed;
					q2.pop();
				}
				else break;
			}
			q.push(temp);
		}

完整代码:

#include<bits/stdc++.h>
using namespace std;
struct kuai
{
	int st;
	int ed;
	int val;
};
int n,d[200002],tempst=1;
queue<kuai> q,q2;
bool vis[200001];
int main()
{
//	freopen("fruit.in","r",stdin);
//	freopen("fruit.out","w",stdout);
	cin>>n;
	for(int i=1;i<=n;i++) cin>>d[i];
	if(d[n]==0) d[n+1]=1;
	else d[n+1]=0;
	for(int i=2;i<=n+1;i++)
	{
		if(d[i]!=d[i-1]) 
		{
			q.push((kuai){tempst,i-1,d[i-1]});
			tempst=i;
		}
	}
	int cnt=n;
	while(cnt)
	{
		while(!q.empty())
		{
			kuai temp=q.front();
			q.pop();
			while(vis[temp.st]&&temp.st<=temp.ed) temp.st++;
			if(temp.st>temp.ed) continue;
			cout<<temp.st<<" ";
			cnt--;
			vis[temp.st]=1;
			if(temp.ed==temp.st)continue;
			temp.st++;
			q2.push(temp);
		}
		cout<<endl;
		while(!q2.empty())
		{
			kuai temp=q2.front();
			q2.pop();
			while(!q2.empty())
			{
				kuai temp2=q2.front();
				if(temp2.val==temp.val)
				{
					temp.ed=temp2.ed;
					q2.pop();
				}
				else break;
			}
			q.push(temp);
		}
	}
	return 0;
}

  • 9
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值