加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

九度 1415 不一样的循环队列 【数据结构】

发布时间:2020-12-15 06:30:22 所属栏目:安全 来源:网络整理
导读:题目地址:http://ac.jobdu.com/problem.php?pid=1415 题目描述: 大家都知道数据结构里面有一个结构叫做循环队列。顾名思义,这是一个队列,并且是循环的。但是现在,淘气的囧哥给这个循环队列加上了一些规矩,其中有5条指令: (1)Push K,让元素K进队列。 (2

题目地址:http://ac.jobdu.com/problem.php?pid=1415

题目描述:

大家都知道数据结构里面有一个结构叫做循环队列。顾名思义,这是一个队列,并且是循环的。但是现在,淘气的囧哥给这个循环队列加上了一些规矩,其中有5条指令:

(1)Push K,让元素K进队列。

(2)Pop,对头元素出队列。

(3)Query K,查找队列中第K个元素,注意K的合法性

(4)Isempty,判断队列是否为空。

(5)Isfull,判断队列是否已满。

现在有N行指令,并且告诉你队列大小是M。

输入:

第一行包含两个整数N和M。1<=N,M<=100000。

接下来有N行,表示指令,指令格式见题目描述。

其中元素均在int范围。

输出:

对于指令(1),若队列已满,输出failed,否则不做输出。

对于指令(2),若队列已空,输出failed,否则不做输出。

对于指令(3),输出队列中第K个元素,若不存在,输出failed。

对于指令(4)和(5),则用yes或者no回答。

详情见样例。

样例输入:
12 2
Push 1
Push 2
Push 3
Query 2
Query 3
Isempty
Isfull
Pop
Pop
Pop
Isempty
Isfull
样例输出:
failed
2
failed
no
yes
failed
yes
no

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

int queue[100010];
int N,M;
int front,tail;

void Init(){
	front = 0;
	tail = 0;
}

int Isempty(){
	return (front == tail) ? 1 : 0;
}

int Isfull(){
	return (front == (tail + 1)%M) ? 1 : 0;
}

int Push(int k){
	if (!Isfull()){
		queue[tail] = k;
		tail = (tail + 1) % M;
		return 1;
	}
	return 0;
}

int Pop(){
	if (!Isempty()){
		front = (front + 1) % M;
		return 1;
	}
	return 0;
}

int Query(int k,int * ans){//检查k的合法性 
	if (k > (tail - front + M) % M || k < 1)
		return 0;
	else{
		*ans = queue[(front + k - 1)%M];
		return 1;
	}
}

int main(int argc,char *argv[]) {
	int i,k,ans;
	char ope[10];
	while (scanf("%d%d",&N,&M) != EOF){
		++M;///////////////////////////////
		Init();
		while (N-- != 0){
			scanf("%s",ope);
			if (strcmp(ope,"Push") == 0){
				scanf("%d",&k);
				if (!Push(k)) printf("failedn");
			}
			else if (strcmp(ope,"Pop") == 0){
				if (!Pop()) printf("failedn");
			}
			else if(strcmp(ope,"Query") == 0){
				scanf("%d",&k);
				if (Query(k,&ans)) printf("%dn",ans);
				else printf("failedn");
			}
			else if (strcmp(ope,"Isempty") == 0){
				if (Isempty())
					printf("yesn");
				else
					printf("non");
			}
			else{
				if (Isfull())
					printf("yesn");
				else
					printf("non");
			}
		}
	}
	return 0;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读