1 条题解

  • 0
    @ 2025-8-24 21:36:02

    自动搬运

    查看原文

    来自洛谷,原作者为

    avatar pengym
    **

    搬运于2025-08-24 21:36:02,当前版本为作者最后更新于2017-11-23 10:14:56,作者可能在搬运后再次修改,您可在原文处查看最新版

    自动搬运只会搬运当前题目点赞数最高的题解,您可前往洛谷题解查看更多

    以下是正文


    ####洛谷P2294 [HNOI2005]狡猾的商人 ,神奇做法——贪心

    • 看到大牛都是写的差分约束或带权并查集,本蒟蒻都不太会(还是用差分约束过了的QAQ),但是想出一种贪心的策略,运用神奇的优先队列实现。

    • 思路是:先按左端点为第一排序关键字,再排右端点。之后就开始两两比较,如果左端点相等,就比较右端点,如果相等,就比较值,如果值不同,就直接输出false,否则输出true,如果右端点不等,就把相同的部分抵消掉,把新的区间再压入优先队列。直到不能操作,就输出true。

    • (ps:作为蒟蒻在洛谷的第一篇博客,还是有点小小的激动 QAQ)

    ####下附代码:

    #include<queue>
    #include<cmath>
    #include<cstdio>
    #include<cstring>
    #include<iostream>
    #include<algorithm>
    #define N 1100
    using namespace std;
    inline void read(int &x)
    {
        x=0;
        int p=1;
        char c=getchar();
        while(!isdigit(c)){if(c=='-')p=-1;c=getchar();}
        while(isdigit(c)) {x=(x<<1)+(x<<3)+(c^'0');c=getchar();}
        x*=p;
    
    }//快速读入
    
    int n,m;
    struct node
    {
        int l,r,s;
        bool operator < (const node &h)const
        {
            if(l!=h.l)return l>h.l;
            return r>h.r;
    
    }//重载运算符,确定优先队列的优先级
    
    }tmp;
    priority_queue<node>q;
    int main()
    {
        int t;
        read(t);
        while(t--)
        {    
            while (!q.empty()) q.pop();//多组数据清空
            read(n);read(m);
            if(m==1){printf("true\n");continue;}//其实没必要特判,只是优化一点点
            for(int i=1;i<=m;i++)
            {
                int l,r,s;
                read(tmp.l);read(tmp.r);read(tmp.s);
                q.push(tmp);
            }
            tmp=q.top();//取出第一个
            q.pop();
            while(!q.empty())
            {    
                node tmp1;
                tmp1=q.top();
                q.pop();
                if(tmp.l==tmp1.l)
                {
                    if(tmp.r==tmp1.r)
                    {
                        if(tmp.s!=tmp1.s)
                        {printf("false\n");goto end;}//退出多重循环的小操作
                    }
                    else 
                    if(tmp.r<tmp1.r)
                        q.push((node) {tmp.r+1, tmp1.r, tmp1.s - tmp.s});//将抵消后的部分放入队列
                }
                tmp = tmp1;//继续比
            }
            printf("true\n");
            end:;
        }
        return 0;
    }
    
    • 1

    信息

    ID
    1289
    时间
    1000ms
    内存
    512MiB
    难度
    4
    标签
    递交数
    0
    已通过
    0
    上传者