CSU 1554 SG Value —— 思维

本文介绍了一种基于优先队列的数据结构实现的算法,该算法可以高效地处理SG值的更新与查询操作。通过实例讲解了如何进行插入操作及查询当前集合的SG值,并给出了完整的代码实现。

题目链接:http://acm.csu.edu.cn/csuoj/problemset/problem?pid=1554


Description

The SG value of a set (multiset) is the minimum positive integer that could not be constituted of the number in this set.
You will be start with an empty set, now there are two opertions:
1. insert a number x into the set;
2. query the SG value of current set.

Input

Input contains multiple test cases. Each test case starts with a number N (0 < N <= 1e5) -- the total number of opertions.
The next N lines contain one opertion each.
1 x means insert a namber x into the set;
2 means query the SG value of current set.

Output

For each query output the SG value of current set.

Sample Input

5
2
1 1
2
1 1
2

Sample Output

1
2
3


题解:

设当前的 SG value 为now,插入的值为x。

1.如果x>now, 那么now的值不会改变。把这个数放进集合中;

2.如果x<=now, 那么now += x, 由于此次now的增大,在集合中小于等于now的数,还能够使now继续增大。使得now增大之后,这个数应该从集合中删去。

(可以用优先队列或multiset维护这个集合)



学习之处:

升序的优先队列: priority_queue<LL, vector<LL>, greater<LL> >q;



代码如下:

#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const double eps = 1e-6;
const int INF = 2e9;
const LL LNF = 9e18;
const int mod = 1e9+7;
const int maxn = 20;

priority_queue<LL, vector<LL>, greater<LL> >q;//优先队列的升序写法
LL n, op, x, now;

void init()
{
    while(!q.empty()) q.pop();
    now = 1;
}

void solve()
{
    while(n--)
    {
        scanf("%lld",&op);
        if(op==1)
        {
            scanf("%lld",&x);
            if(x>now)
            {
                q.push(x);
                continue;
            }

            now += x;
            while(!q.empty() && now>=q.top())
            {
                now += q.top();
                q.pop();
            }
        }
        else printf("%lld\n", now);
    }
}

int main()
{
    while(scanf("%lld",&n)!=EOF)
    {
        init();
        solve();
    }
    return 0;
}


转载于:https://www.cnblogs.com/DOLFAMINGO/p/7538690.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值