Hdoj 1509 -Windows Message Queue 优先队列最小堆实现

一开始提交后得到了好几个WA,搞得我一直很郁闷,于是重新看了一下题目,发现有一个地方我没有考虑到

Note that one message can appear twice or more and if two messages have the same priority, the one comes first will be processed first.(i.e., FIFO for the same priority.)

意思是一段信息可以重复出现,并且如果两串信息的优先级相同,则输出先输入的字符串

 

思路:建立一个最小堆,维护字符串的优先级,其中维护操作如下:

  1. 如果两串字符串的优先级相同,则维护字符串的编号(显然按编号最小优先)
  2. 如果两串字符串的优先级不同,直接维护字符串的优先级(显然按优先级最小优先)

Code

AC  46ms  228k

#include <stdio.h>
#include <string.h>

const int maxn = 60004;
const int INF  = 0x3F3F3F3F;

struct MesQueue
{
    int  argu, w, num;
    char meg[10];
}heap[maxn];

int  n=0, cnt=0;
char cmd[10];

bool cmp(struct MesQueue x, struct MesQueue y)
{
    if (x.w == y.w)
        return (x.num>y.num ? 1:0);
    else
        return (x.w>y.w ? 1:0);
}/* cmp */

void shiftdown(int k, int n)    /* From top to bottom */
{
    int son;
    struct MesQueue key = heap[k];  /* key=heap[k].w */
    
    for (; k<=n>>1; k=son)
    {
        son = k<<1;
        if (k!=n && cmp(heap[son], heap[son+1]))
            son = son + 1;
        
        if (cmp(key, heap[son]))
            heap[k] = heap[son]; 
        else
            break;
    }/* End of For */
    heap[k] = key;
}/* shiftdown */

void GetHeapTop()
{
    printf("%s %d\n", heap[1].meg, heap[1].argu);
    
    heap[1] = heap[n];
    
    heap[n].w = INF;
    heap[n].num = 0;
    heap[n].argu = 0;
    strcpy(heap[n].meg, "\0");

    shiftdown(1, --n);
}/* GetHeapTop */

void InsertHeap()
{
    ++n;    /* number of node in heap increase one */
    ++cnt;  /* Mark of node in heap */
    
    scanf("%s %d %d", &heap[n].meg, &heap[n].argu, &heap[n].w);
    heap[n].num = cnt;
    
    int p = n; /* heap[p>>1].w>tmp.w */
    struct MesQueue tmp = heap[n];
    
    while (p!=1 && cmp(heap[p>>1], tmp))    /* From bottom to top */
    {
        heap[p] = heap[p>>1];
        p >>= 1;
    }/* End of While */
    heap[p] = tmp;
}/* InsertHeap */

int main()
{
    while (~scanf("%s", cmd))
    {
        if (cmd[0] == 'G')
        {   /* GET */
            if (n == 0)
                printf("EMPTY QUEUE!\n");
            else
                GetHeapTop();
        }/* End of IF */
        else
        {
            InsertHeap();
        }
    }/* End of While */
    
    return 0;
}

 

转载于:https://www.cnblogs.com/yewei/archive/2012/05/05/2484643.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值