zoukankan      html  css  js  c++  java
  • 贪心算法 ()

    English foundation:

    do some cleaning chores

    题目:https://cn.vjudge.net/contest/317575#problem/A

    Hint:

    This problem has huge input data,use scanf() instead of cin to read data to avoid time limit exceed. 

    分析:

    #include<iostream>
    #include<cstdio>
    #include<cstring>
    using namespace std;

    int n,t;
    struct node
    {
    int a,b;
    }q[1<<20];

    bool cmp(node x,node y)
    {
    return x.a<y.a||(x.a==y.a && x.b>y.b);
    }

    int main()
    {
    while(~scanf("%d%d",&n,&t))
    {
    for(int i=0;i<n;i++)
    {
    scanf("%d%d",&q[i].a,&q[i].b);
    }
    sort(q,q+n,cmp);

    if(q[0].a!=1)
    {
    puts("-1");
    continue;
    }

    int ans=1;
    int r=q[0].b;//r代表已买最右
    int nowr=q[0].b;//nowr代表已遍历的最右

    for(int i=1;i<n;i++)
    {
    //出现断点了
    if(q[i].a>r+1)
    {
    r=nowr;
    ans++;
    }

    if(q[i].a<=r+1)
    {
    if(q[i].b>nowr) nowr=q[i].b;//已遍历的最右

    if(q[i].b==t)//不断贪心最右,直至贪到右边界
    {
    r=t;
    ans++;
    break;
    }
    }
    }
    if(r==t) printf("%d ",ans);
    else puts("-1");
    }
    return 0;
    }

      

    参考:

    https://blog.csdn.net/zwj1452267376/article/details/50420633

    https://blog.csdn.net/Code92007/article/details/82912887

  • 相关阅读:
    git 常用命令
    mac 显示隐藏文件
    android 图片缓存
    字符串与枚举相互转换
    ios 消息通知
    ios 真机调试
    ios 宏定义 系统版本 判定
    autolayout autoresizing
    c++对象创建带括号与无括号的区别
    内存对齐
  • 原文地址:https://www.cnblogs.com/dragondragon/p/11358741.html
Copyright © 2011-2022 走看看