OJ提交地址:https://www.luogu.org/problemnew/show/P1540算法
http://noi.openjudge.cn/ch0112/07/数组
小晨的电脑上安装了一个机器翻译软件,他常常用这个软件来翻译英语文章。ide
这个翻译软件的原理很简单,它只是从头至尾,依次将每一个英文单词用对应的中文含义来替换。对于每一个英文单词,软件会先在内存中查找这个单词的中文含义,若是内存中有,软件就会用它进行翻译;若是内存中没有,软件就会在外存中的词典内查找,查出单词的中文含义而后翻译,并将这个单词和译义放入内存,以备后续的查找和翻译。spa
假设内存中有M个单元,每单元能存放一个单词和译义。每当软件将一个新单词存入内存前,若是当前内存中已存入的单词数不超过M−1,软件会将新单词存入一个未使用的内存单元;若内存中已存入M 个单词,软件会清空最先进入内存的那个单词,腾出单元来,存放新单词。翻译
假设一篇英语文章的长度为N个单词。给定这篇待译文章,翻译软件须要去外存查找多少次词典?假设在翻译开始前,内存中没有任何单词。code
样例 #1: 3 7 1 2 1 5 4 4 1 样例 #2: 2 10 8 824 11 78 11 78 11 78 8 264
样例 #1: 5 样例 #2: 6
算法分析:blog
用队列先进先出的特性模拟内存存放单词;用一个一维数组标记某一个单词是否在于内存中以便快速肯定是否须要查找词典。其他的基本就是纯粹模拟了。队列
有一点须要注意:如果使用循环队列,须要好好检查循环队列中元素个数的计算是否正确。内存
代码一:不使用循环队列,直接把队列定义得足够大io
1 #include<stdio.h> 2 #define maxQueueLength 1005 3 int main() 4 { 5 int M,N; 6 int que[maxQueueLength]={0},check[1005]={0}; // que[]是循环队列,用来模拟内存;check[i]==1表示i在内存中。 7 int ans=0,begin,end,i,t; 8 scanf("%d%d",&M,&N); 9 10 begin=end=0;//初始化队列 11 for(i=0;i<N;i++) 12 { 13 scanf("%d",&t); 14 if(check[t]==0)//查找内存,发现内存中没有t存在 15 { 16 ans++;//查找字典的次数增长一次 17 //如今开始作单词放进内存的过程 18 if(end-begin<M) 19 { 20 que[end++]=t; 21 } 22 else //end-begin>=M 23 { 24 check[que[begin]]=0; 25 begin++; 26 que[end++]=t; 27 } 28 check[t]=1;//标记t已经在内存中 29 } 30 } 31 printf("%d\n",ans); 32 return 0; 33 }
代码二:使用循环队列,节省一些队列空间
1 #include<stdio.h> 2 #define maxQueueLength 105 3 int main() 4 { 5 int M,N; 6 int que[maxQueueLength]={0},check[1005]={0}; // que[]是循环队列,用来模拟内存;check[i]==1表示i在内存中。 7 int ans=0,begin,end,i,t,count; 8 9 scanf("%d%d",&M,&N); 10 11 begin=end=0;//初始化队列 12 for(i=0;i<N;i++) 13 { 14 scanf("%d",&t); 15 if(check[t]==0)//查找内存,发现内存中没有t存在 16 { 17 ans++;//查找字典的次数增长一次 18 //如今开始作单词放进内存的过程 19 if(end>=begin) count=end-begin; 20 else count=maxQueueLength-begin+end; 21 22 if(count<M) 23 { 24 que[end++]=t; 25 if(end>=maxQueueLength) end=end%maxQueueLength; 26 } 27 else //end-begin>=M 28 { 29 check[que[begin]]=0; 30 begin++; 31 que[end++]=t; 32 if(begin>=maxQueueLength)begin=begin%maxQueueLength; 33 if(end>=maxQueueLength)end=end%maxQueueLength; 34 } 35 check[t]=1;//标记t已经在内存中 36 } 37 } 38 printf("%d\n",ans); 39 return 0; 40 }
下面的代码也是用了循环队列,不过代码的可读性可能好一些哈哈哈
1 #include <stdio.h> 2 #include <stdlib.h> 3 4 int main() 5 { 6 int m,n; 7 int i; 8 int a[102]={0},count=0;//a[]表示内存的空间。count记录当前内存中已经存有的单词个数 9 int firstIn=0,lastIn=0;//firstIn表示最先进入内存的单词在内存中的下标。lastIn表示下一个能够用于存储新单词的空闲空间的下标。 10 int b[1005]={0};//b[i]==1表示i这个单词在内存中。不然表示i不在内存中。 11 int ans=0,t; 12 13 scanf("%d%d",&m,&n); 14 for(i=0;i<n;i++) 15 { 16 scanf("%d",&t);//依次输入n个单词 17 if(b[t]==0)//若单词t不在内存中 18 { 19 ans++;//须要查一次字典 20 21 //查完字典后须要把刚查的单词存入内存 22 if(count<m)//内存空间还有空闲 23 { 24 a[lastIn]=t; 25 b[t]=1; 26 count++; 27 lastIn++; 28 lastIn=lastIn%m; 29 } 30 else//内存空间已经满了 31 { 32 //先腾空一个位置 33 b[a[firstIn]]=0; 34 //a[firstIn]=0; 35 firstIn++; 36 firstIn=firstIn%m; 37 38 //而后再把新单词放入内存 39 a[lastIn]=t; 40 b[t]=1; 41 lastIn++; 42 lastIn=lastIn%m; 43 } 44 } 45 } 46 printf("%d\n",ans); 47 return 0; 48 }