codeforces371D 并查集

There is a system of n vessels arranged one above the other as shown in the figure below. Assume that the vessels are numbered from 1 to n, in the order from the highest to the lowest, the volume of the i-th vessel is a i liters.
在这里插入图片描述

Initially, all the vessels are empty. In some vessels water is poured. All the water that overflows from the i-th vessel goes to the (i + 1)-th one. The liquid that overflows from the n-th vessel spills on the floor.

Your task is to simulate pouring water into the vessels. To do this, you will need to handle two types of queries:

Add x i liters of water to the p i-th vessel;
Print the number of liters of water in the k i-th vessel.
When you reply to the second request you can assume that all the water poured up to this point, has already overflown between the vessels.

Input
The first line contains integer n — the number of vessels (1 ≤ n ≤ 2·105). The second line contains n integers a 1, a 2, …, a n — the vessels’ capacities (1 ≤ a i ≤ 109). The vessels’ capacities do not necessarily increase from the top vessels to the bottom ones (see the second sample). The third line contains integer m — the number of queries (1 ≤ m ≤ 2·105). Each of the next m lines contains the description of one query. The query of the first type is represented as “1 p i x i”, the query of the second type is represented as “2 k i” (1 ≤ p i ≤ n, 1 ≤ x i ≤ 109, 1 ≤ k i ≤ n).

Output
For each query, print on a single line the number of liters of water in the corresponding vessel.

Examples
Input
2
5 10
6
1 1 4
2 1
1 2 5
1 1 4
2 1
2 2
Output
4
5
8

题目大意:有N个叠起来的盘子,上方盘子中的水如果满了会留到下方盘子里,如果最下面的也满了会留到地上,现在从上到下告诉你盘子的容积,然后又Q次操作,操作分为两种:1.往第K个盘子里倒C的水,2.查询第K个盘子里有多少水。

a数组记录每个盘子容积,ans数组记录每个盘子里的水,如果倒的水超过盘子的容积就把盘子和下一个盘子通过并查集连接在一起。

#include<iostream>
using namespace std;
int a[200010],ans[200010];
int f[200010];
int find(int x)
{
	return f[x]==x?x:f[x]=find(f[x]);
} 
void add(int x,int y)
{
	int t1=find(x);
	int t2=find(y);
	f[t1]=t2;
}
int main()
{
	int n,q;
	cin>>n;
	for(int i=1;i<=n;i++)
	{
		cin>>a[i];
		f[i]=i;
	}
	f[n+1]=n+1;//边界+1处理水溢出 
	cin>>q;
	while(q--)
	{
		int t;
		cin>>t;
		if(t==1)
		{
			int k,c;
			cin>>k>>c;
			while(c)
			{
				k = find(k);
				if(k>n)
				break;
				if (ans[k]+c>=a[k])
				{
					c-=(a[k]-ans[k]);
					ans[k]=a[k];
					add(k,k+1);//本层已满,合并到下一层 
				}
				else
				{
					ans[k]+=c;
					c=0;
				}
			}
		}
		else
		{
			int k;
			cin>>k;
			cout<<ans[k]<<endl;
		}
	}	
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值