赞
踩
小晨的电脑上安装了一个机器翻译软件,他经常用这个软件来翻译英语文章。
这个翻译软件的原理很简单,它只是从头到尾,依次将每个英文单词用对应的中文含义来替换。
对于每个英文单词,软件会先在内存中查找这个单词的中文含义,如果内存中有,软件就会用它进行翻译;如果内存中没有,软件就会在外存中的词典内查找,查出单词的中文含义然后翻译,并将这个单词和译义放入内存,以备后续的查找和翻译。
假设内存中有 M 个单元,每单元能存放一个单词和译义。
每当软件将一个新单词存入内存前,如果当前内存中已存入的单词数不超过 M−1,软件会将新单词存入一个未使用的内存单元;若内存中已存入 M 个单词,软件会清空最早进入内存的那个单词,腾出单元来,存放新单词。
假设一篇英语文章的长度为 N 个单词。
给定这篇待译文章,翻译软件需要去外存查找多少次词典?
假设在翻译开始前,内存中没有任何单词。
输入文件共 2 行,每行中两个数之间用一个空格隔开。
第一行为两个正整数 M 和 N,代表内存容量和文章的长度。
第二行为 N 个非负整数,按照文章的顺序,每个数(大小不超过 1000)代表一个英文单词。
文章中两个单词是同一个单词,当且仅当它们对应的非负整数相同。
输出文件共 1 行,包含一个整数,为软件需要查词典的次数。
0<M≤100,
0<N≤1000
- 3 7
- 1 2 1 5 4 4 1
5
- #include<iostream>
- using namespace std;
-
- #define M 10000
- #define N 1000000
-
- //创建队列(表示内存空间)
- int Queue[M] = {0};
- int front = -1; //队列头
- int rear = -1; //队列尾
-
- int m,n,count_of_text=1;
- int dictionary_count = 0;
-
- int main()
- {
- int text; //保存每次读入的单词
- cin>>m>>n;
- if(m<0&&m>M || n<0&&n>N)
- {
- cout<<"OVERFLOW"<<endl;
- exit(0);
- }
- while(count_of_text<=n)
- {
- bool flag = 0;
- cin>>text;
- if(rear == front) //队列为空
- {
- Queue[++rear] = text; //入队
- dictionary_count++;
- }
- else if(rear-front < m) //队列不满
- {
- for(int i=front+1; i<=rear; i++) //查找当前内存中是否已经存在该文本
- {
- if(Queue[i] == text)
- {
- flag = 1;
- break;
- }
- }
- if(!flag) //若当前内存中不存在该文本
- {
- Queue[++rear] = text; //入队
- dictionary_count++;
- }
- }
- else //队列满
- {
- for(int i=front+1; i<=rear; i++) //查找当前内存中是否已经存在该文本
- {
- if(Queue[i] == text)
- {
- flag = 1;
- break;
- }
- }
- if(!flag) //若当前内存中不存在该文本
- {
- Queue[++front] = 0; //先将队首出队
- Queue[++rear] = text; //再入队
- dictionary_count++;
- }
- }
- count_of_text++;
- }
- cout<<dictionary_count<<endl;
- return 0;
- }

用bool数组存储每个单词是否已经在队列中,这样就可以用 O(1) 的时间判断每个单词是否已在缓存中了。(空间换时间的思想)
C++的STL中的queue真好用,嘻嘻。
- #include <iostream>
- #include <queue>
-
- using namespace std;
-
- const int N = 1010;
-
- int m, n;
- bool st[N] = {0}; //空间换时间的思想
-
- int main()
- {
- cin >> m >> n;
-
- queue<int> q;
- int res = 0;
-
- for (int i = 0; i < n; i ++ )
- {
- int x;
- cin >> x;
- if (!st[x])
- {
- if (q.size() == m)
- {
- int t = q.front();
- st[t] = false;
- q.pop();
- }
-
- q.push(x);
- st[x] = true;
- res ++ ;
- }
- }
-
- cout << res << endl;
- return 0;
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。