P1540 机器翻译

题目

  1. 用vector模拟内存
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main()
{
    int m,n;
    cin>>m>>n;
    
    vector<int> v;			//使用vector模拟内存 
    int res=0;
    for(int i=0;i<n;i++)
    {
        int x;
        cin>>x;
        
        if(find(v.begin(), v.end(),x) == v.end()) // find()函数 在<algorithm>里 
        {
            res++;
            v.push_back(x);
        }
        if(v.size()>m) v.erase(v.begin());
    }
    cout<<res;
    
    return 0;
}
  1. 数组模拟队列
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

const int N = 1010;

int a[N],b[N]; // b数组模拟队列 

int main()
{
    int m,n;
    cin>>m>>n;
    
    int res=0;
    int hh=0,tt=-1;
    for(int i=0;i<n;i++)
    {
        int x;
        cin>>x;

        if(!a[x]) // x如果不在内存中
        {
        	res++; // 查找+1;
        	a[x]=1; // 调入内存
        	b[++ tt]=x; // 队列+1
        	if(tt - hh + 1 > m )  a[b[hh ++]] = 0; // 队列容量为m
		}
    }
    cout<<res;
    
    return 0;
}
  1. 直接使用STL里的queue
#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>

using namespace std;

const int N = 1010;

int a[N],b[N]; // b数组模拟队列 
queue<int> q;

int main()
{
    int m,n;
    cin>>m>>n;
    
    int res=0;
    //int hh=0,tt=-1;
    for(int i=0;i<n;i++)
    {
        int x;
        cin>>x;

        if(!a[x]) // x如果不在内存中
        {
        	res++; // 查找+1;
        	a[x]=1; // 调入内存
        	//b[++ tt]=x; // 队列+1
        	q.push(x);
        	//if(tt - hh + 1 > m )  a[b[hh ++]] = 0; // 队列容量为m
        	if(q.size() > m) {
        	    int t=q.front();
        	    a[t]=0;
        	    q.pop();
        	}
		}
    }
    cout<<res;
    
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值