Okabe and Boxes CodeForces

来源:互联网 发布:mac 五笔输入法 联想 编辑:程序博客网 时间:2024/05/01 21:11

题意 :共n个数字,一共2n个操作,分别为add和remove。 add 压入数字, remove删除数字,要求从1删到n,保证数据合理。

思路:对于add ,就压入vector , 对于remove,如果当前最后一个数字是所需要删除的now, 那么我们就sort一遍(保证次数最少),这样复杂度就是O(n*nlogn),会超时。
那么怎么解决sort的问题呢? 当back!=now的时候,这时我们假装sort一下,如何做到等效sort,那就是a.clear();其实在a.clear()过程中,逻辑上我们可以认为已经是有序的,并且从大到小排序,虽然把a里的元素都删除了,但我们可以等效为已经排好序列了,如果是a.empty(),则说明前面已经排好序了,当前的情况是合理的。如果!a.empty(),则判断一下back==now? a.pop() : a.clear();大功告成。在AC代码下面贴上TLE代码。

#include <iostream>#include <stdio.h>#include <vector>#include <algorithm>using namespace std;typedef long long ll;const int maxn=3e5+50;vector <int >a;bool cmp(const int a,const int b){    return a>b;}int ans=0;int main(void){    int n;    int now=0;    cin >> n;    int index=1;    for(int i=1; i<=2*n; i++)    {        char str[5];        scanf("%s",str);        if(str[0]=='a')        {            int x;            scanf("%d",&x);            a.push_back(x);        }        else if(str[0]=='r')        {            now++;            if(!a.empty())            {                if(a.back()!=now)                {                    a.clear();                    ans++;                }                else if(a.back()==now)                    a.pop_back();            }            else if(a.empty())                continue ;        }    }    cout << ans << endl;    return 0;}

TLE

#include <iostream>#include <stdio.h>#include <vector>#include <algorithm>using namespace std;typedef long long ll;const int maxn=3e5+50;vector <int >a;bool cmp(const int a,const int b){    return a>b;}int ans=0;int main(void){    int n;    int now=1;    cin >> n;    int index=1;    for(int i=1; i<=2*n; i++)    {        char str[5];        scanf("%s",str);        if(str[0]=='a')        {            int x;            scanf("%d",&x);            a.push_back(x);        }        else if(str[0]=='r')        {            if(a[a.size()-1]!=now)            {                ans++;                sort(a.begin(),a.end(),cmp);            }            a.pop_back();            now++;        }    }    cout << ans << endl;}

// 其实这两段程序的本质是一样的。首先我们要明确一点,题目的数据给的都是绝对合理的。TLE的代码是,每次都对back!=now的情况进行sort,优化了的代码是把back!=now情况下,a.clear(),在逻辑上认为已经sort过,对于当前的remove,如果a是空的,那么肯定是可以的;如果不是空的,则比较back和now的关系,再做决策。 优化的关键在于把sort()等价为clear(),很奇妙的思路…!

原创粉丝点击