1009 训练课 错题集 黄梓涵 队列

· · 个人记录

D46747 长长队列

(原题名: Large Queue )

⌨ 完整代码

#include<bits/stdc++.h>
using namespace std;
#define int long long
struct noob
{
    int c;
    int x;
};
deque<noob>q;
signed main() {

    ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
    int Q;
    cin>>Q;
    while(Q--)
    {
        int xx,cc;
        int a;
        cin>>a;
        if(a==1)
        {
            cin>>cc>>xx;
            q.push_back({cc,xx}); 
        }
        else
        {
            int sum=0;
            int k;
            cin>>k;
            while(k!=0)
            {
                if(k>=q.front().c)
                {
                    sum+=q.front().c*q.front().x;
                    k-=q.front().c;
                    q.pop_front();
                }
                else
                {
                    sum+=k*q.front().x;
                    noob yt={q.front().c-k,q.front().x};
                    q.pop_front();
                    q.push_front(yt);
                    k=0; 
                }
            }
            cout << sum << "\n";
        }
    }

    return 0;
}                                                       

🧠思路问题

:::epigraph[……吧?] 这道题,是一道基本的队列题。你只需按它的操作删元素/插元素,应该不需我讲 ::: 这道题目插入的东西十分多,一不留神队列的时间和空间就会爆炸。 一次就插1e9个数,是吗!? 那么——

上吧!结构体队列!

struct noob
{
    int x; //插入的数
    int c; //插入了多少个
};
deque<noob>q;

这就简单了,对于插入,只需要 q.push_back(c,x); ,对于删除,需要 while(k!=0) ( k 为删除的次数)

然后:如果队头的 c 小于 k ,那么 sum+=(k*q.front().x);q.front().c-=k;k=0; 。否则,sum+=(q.front().c*q.front().x);k-=q.front().c;q.pop_front();

D3486 接水问题

⌨ 完整代码

#include<bits/stdc++.h>
using namespace std;
int a[105];
int main() {

    ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
    int n,m;
    cin>>n>>m;
    for(int i=1;i<=n;i++)
    {
        int x;
        cin>>x;
        sort(a+1,a+1+m);
        a[1]+=x;
    }
    sort(a+1,a+1+m);
    cout << a[m];

    return 0;
}                                                       

🧠思路问题

接水顺序是确定的,水龙头给哪一个人供水随便。

因此先让 m 个人霸占 m 个水龙头,剩下 n-m 个人分别按排队顺序选择时间花费最小的水龙头

D46748 数字拼接

⌨ 完整代码

#include<bits/stdc++.h>
using namespace std;

int main() {

    ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
    int t;
    cin>>t;
    while(t--)
    {
        priority_queue<string>q;
        int n,w=0;
        cin>>n;
        for(int i=1;i<=n;i++)
        {
            string s;
            cin>>s;
            q.push(s);
            w+=s.size();
        }
        string ans=""; 
        for(int i=1;i<=w;i++)
        {
            string s=q.top();
            ans+=s[0];
            s.erase(0,1);
            q.pop();
            q.push(s);
        }
        cout << ans << "\n";
    }

    return 0;
}

🧠思路问题

用优先队列,存储 string 类型,大根堆,默认ASCLL码最大的就是队头。每次输出队头的第一个字符,然后把队头的第一个字符删掉,循环往复,就可以了。