手工数据结构系列-C语言模拟队列 hdu1276

本文介绍了一个基于数组实现的动态队列数据结构,并通过一个具体的竞赛题目来展示如何使用该队列进行操作。包括队列的基本操作如入队、出队、判断空队列等,以及如何在竞赛中解决特定问题。
#include <stdio.h>
#include <stdlib.h>
#define init_size 1000
typedef struct {
    int head,tail,size,__size,*seq;
}Queue;
typedef Queue* Q_P;
void init(Q_P q){
    q->head=q->tail=0;q->__size=init_size;q->size=0;
    q->seq=(int*)malloc(init_size*sizeof(Queue));
}
void push(Q_P q,int ele){
    if(q->tail+1>=q->__size){
        q->seq=(int*)realloc(q->seq,sizeof(int)*(q->__size*=2));
    }
    q->seq[q->tail++]=ele;
    q->size++;
    //debug
    // printf("PUSH %d SIZE:%d\n",q->seq[q->tail-1],q->size);
}
int empty(Q_P q){
    if(q->head==q->tail) return 1;
    return 0;
}
void pop(Q_P q){
    if(!empty(q)) q->head++,q->size--;
    // printf("POP SIZE:%d\n",q->size);
}
int front(Q_P q){
    if(!empty(q)) return q->seq[q->head];
}
void print(Q_P q){
    printf("%d",front(q));pop(q);
    while(q->size!=0) {printf(" %d",front(q));pop(q);}
    printf("\n");
}
void test(){
    int i;
    Q_P q=(Q_P)malloc(sizeof(Queue));
    init(q);
    for(i=0;i<10;++i) {push(q,i);}
    print(q);    
}
void solve(){
    int n,i,T;scanf("%d",&T);
    while(T--){
        scanf("%d",&n);
        Q_P a=(Q_P)malloc(sizeof(Queue)),b=(Q_P)malloc(sizeof(Queue));//或者Queue *a,*b;
        init(a);init(b);
        for(i=1;i<=n;++i){
                push(a,i);push(b,i);
        }
        // print(a);print(b);
        //print the Queue ,but at the same time the action does clear the queue
        if(a->size!=0&&a->size<=3) print(a);
        int cnt=0;
        while(a->size>3||b->size>3){
            int k;
            for(k=2;k<=3;++k){
                cnt++;
                if(cnt&1){
                    while(b->size!=0) pop(b);
                    int cc=0;while(a->size!=0) {if(++cc%k!=0) push(b,front(a));pop(a);}
                }
                else{
                    while(a->size!=0) pop(a);
                    int cc=0;while(b->size!=0) {if(++cc%k!=0) push(a,front(b));pop(b);}
                }
                if(a->size!=0&&a->size<=3) {print(a);break;}
                if(b->size!=0&&b->size<=3) {print(b);break;}
            }
        }
    } 
}

int main(){
    // test();
    solve();
    return 0;
}

 

转载于:https://www.cnblogs.com/linkzijun/p/6498524.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值