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

  • 相关阅读:
    C# Using MySQL
    C++ Asynchronous IO on Windows
    C++ Bind adapter usage
    C# Entity Framework with MSSQL, MYSQL
    Read a file into array for C++/C#
    上下移动 04.16
    盒子模型001基础
    JavaScript&JQ 001_五角星评分
    jQuery EasyUI tree的 使用
    自定义实现URL重写 04.18
  • 原文地址:https://www.cnblogs.com/dragondragon/p/11358741.html
Copyright © 2011-2022 走看看