zoukankan      html  css  js  c++  java
  • Codeforces 681C:Heap Operations

      

    Heap Operations

    题目链接:

    http://codeforces.com/contest/681/problem/C

    题意:

    有个堆,有三种操作

    • insert x — 把x加到堆里
    • getMin x — 得到堆里的最小值,且最小值等于x     当堆为空或者最小值不等于x时操作违法
    • removeMin — 删除堆里的最小值                       当堆为空时操作违法

     题目给出了一些操作,不一定合法,往里再添加一些操作使得所有的操作都合法,求添加操作最少的情况并按序输出全部操作(新添加的和已存在的)

    题解:

    优先队列模拟操作

       当前操作为insert x时向队列中加入x

       当前操作为removeMin时将队列的top()删除,若队列为空则在removeMin前先insert一个在x的定义域内的任意值就好了

       当前操作为getMin x时:如果队列为空,则先insert x

                   如果队列不为空,则比较队列的top()和x的大小关系,只要top()小于x就一直removeMin,在此之后若top()大于x或队列为空,则insert x

                 

    代码

    #include<stdio.h>
    #include<map>
    #include<queue>
    using namespace std;
    struct Node
    {
      char ss;
      int x;
    }t[1000005];
    char s[20];
    struct node
    {
      int x;
      node(int a=0)
      {
        x=a;
      }
      bool friend operator<(node a,node b)
      {
        return a.x>b.x;
      }
    };
    priority_queue<node>w;
    int main()
    {
      int n,x,num=0;
      while(!w.empty())w.pop();
        scanf("%d",&n);
      for(int i=1;i<=n;++i)
      {
        scanf("%s",s);
        if(s[0]=='i')
        {
          scanf("%d",&x);
          t[num].ss='i';
          t[num++].x=x;
          w.push(node(x));
        }
        else if(s[0]=='g')
        {
          scanf("%d",&x);
          while(!w.empty())
          {
            if(w.top().x<x)
            {
              t[num++].ss='r';
              w.pop();
            }
            else break;
          }
          if(w.empty()||w.top().x!=x)
          {
            t[num].ss='i';
            t[num++].x=x;
            w.push(node(x));
          }
          t[num].ss='g';
          t[num++].x=x;
        }
        else
        {
          if(!w.empty())
          {
            t[num++].ss='r';
            w.pop();
          }
          else
          {
            t[num].ss='i';
            t[num++].x=1;
            t[num++].ss='r';
          }
        }
      }
      printf("%d ",num);
      for(int i=0;i<num;++i)
        if(t[i].ss=='r')
          printf("removeMin ");
      else if(t[i].ss=='g')printf("getMin %d ",t[i].x);
      else printf("insert %d ",t[i].x);
    }

     

      

  • 相关阅读:
    JS方法集
    IOC 在Mvc中的使用
    ExtJS4 便捷三层开发模式
    Net Framework中的提供的常用委托类型
    作用域、作用域链理解
    Swing中弹出对话框的几种方式(转)
    程序员的价值观——经验是无价之宝(转)
    透过浏览器看HTTP缓存(转)
    模态窗口其实就是在当前窗口调用系统的消息循环,响应用户的操作,将相关的消息发送到对应的窗口(转)
    开发小结(转)
  • 原文地址:https://www.cnblogs.com/kiuhghcsc/p/5596790.html
Copyright © 2011-2022 走看看