杭電1702 ACboy needs your help again!

考點:本題考查棧和隊列的結合使用

題意:有多個測試數據。如果輸入的數據採用先進先出(即題中的FIFO)則用隊列方式進行存儲並輸出,這種方式存入隊列時只要修改尾指針rear(尾指針+1),輸出時修改頭指針front(頭指針+1),判斷隊列爲空用(rear-front=0)。

如果採用先進後出(即題中的FILO),則用棧方式進行存儲並輸出,這種方式進棧時修改棧頂指針toptop+1),出棧時一定注意先取棧頂元素,然後再top--,進棧則是先top++,再向棧中放入元素。

ACboy needs your help again!

Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2900 Accepted Submission(s): 1507


Problem Description
ACboy was kidnapped!!
he miss his mother very much and is very scare now.You can't image how dark the room he was put into is, so poor :(.
As a smart ACMer, you want to get ACboy out of the monster's labyrinth.But when you arrive at the gate of the maze, the monste say :" I have heard that you are very clever, but if can't solve my problems, you will die with ACboy."
The problems of the monster is shown on the wall:
Each problem's first line is a integer N(the number of commands), and a word "FIFO" or "FILO".(you are very happy because you know "FIFO" stands for "First In First Out", and "FILO" means "First In Last Out").
and the following N lines, each line is "IN M" or "OUT", (M represent a integer).
and the answer of a problem is a passowrd of a door, so if you want to rescue ACboy, answer the problem carefully!

Input
The input contains multiple test cases.
The first line has one integer,represent the number oftest cases.
And the input of each subproblem are described above.

Output
For each command "OUT", you should output a integer depend on the word is "FIFO" or "FILO", or a word "None" if you don't have any integer.

Sample Input
4 4 FIFO IN 1 IN 2 OUT OUT 4 FILO IN 1 IN 2 OUT OUT 5 FIFO IN 1 IN 2 OUT OUT OUT 5 FILO IN 1 IN 2 OUT IN 3 OUT

Sample Output
1 2 2 1 1 2 None 2 3

代碼
#include<stdio.h>
#include<string.h>
int main()
{
	int i,n,top,m,t,front,rear,q,s[100];//用數組表示棧和隊列
	char f[100],p[100];//用於存儲進出棧和隊列的方式(IN或OUT)
	scanf("%d",&n);
	{
		while(n--)
		{
			scanf("%d%s",&m,&f);
			top=rear=front=0;//初始時全部爲0 
			while(m--)
			{
				scanf("%s",&p);
				if(strcmp(f,"FIFO")==0)//隊列
				{		
					if(strcmp(p,"IN")==0)//入隊
					{
						scanf("%d",&t);
						s[rear++]=t;
					}
					else if(strcmp(p,"OUT")==0)//出隊
					{
						if((rear-front)==0)//判隊空
							printf("None\n");
						else //隊不空
							q=s[front++];
							printf("%d\n",q);
					}
				}
				else //棧
				{
					if(strcmp(p,"IN")==0)
					{
						scanf("%d",&t);
						s[top++]=t;
					}
					else 
					{
						if(top<=0)
							printf("None\n");
						else
							printf("%d\n",s[--top]);//這裏一定要注意先輸出棧頂元素,再												移動top指針
					}
				}
			}	
		}
	}
	return 0;
}

總結

這道題很好地介紹了棧和隊列兩種數據結構的應用,關鍵就是指針的修改,以及一些特殊情況,如棧空、隊空。它不像我們以前嚴蔚敏數據結構學習中的類c語言代碼一樣很長,所以理解起來比較簡單。另外,就是對於所有情況要考慮全面。



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章