Codeforces Round #218 (Div. 2) D. Vessels(思维 并查集)

题意:从上到下有n个杯子,编号从1到n。每个杯子有一定体积v[i]. 两种操作:1 x y, 向x水杯倒y水; 2 x, 询问x水杯有多少水. (水杯水溢出会往下流)

n,q <= 2e5

思路:暴力倒水的话是n*q,很多次要经过满的水杯,很费时,可以用并查集维护每个水杯往下的第一个非满的水杯。


代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn = 1e6+5;
int a[maxn], cur[maxn], pre[maxn];

int Find(int x)
{
    int r = x;
    while(pre[r] != r) r = pre[r];
    int i = x, j;
    while(pre[i] != r)
    {
        j = pre[i];
        pre[i] = r;
        i = j;
    }
    return r;
}

void join(int x, int y)
{
    int a = Find(x);
    int b = Find(y);
    if(a > b)
        pre[b] = a;
    else
        pre[a] = b;
}

int main(void)
{
    int n;
    while(cin >> n)
    {
        memset(cur, 0, sizeof(cur));
        for(int i = 1; i <= n; i++)
            scanf("%d", &a[i]), pre[i] = i;
        pre[n+1] = n+1;
        int q;
        scanf("%d", &q);
        while(q--)
        {
            int cmd, x, y;
            scanf("%d%d", &cmd, &x);
            if(cmd == 1)
            {
                scanf("%d", &y);
                while(y)
                {
                    int t = Find(x);
                    if(t == n+1) break;
                    if(a[t]-cur[t] >= y)
                    {
                        cur[t] += y;
                        y = 0;
                    }
                    else
                    {
                        y -= a[t]-cur[t];
                        cur[t] = a[t];
                        join(t, t+1);
                    }
                    x = t;
                }
            }
            else printf("%d\n", cur[x]);
        }
    }
    return 0;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值