描述
实现页面置换算法
第一行:N, M, N代表访问页面次数,M代表页框数
第二行:N个访问页面的页面号
输出:页框变化和缺页中断数
sampleInput
10 3
8 9 10 11 23 8 10 23 9 1
sampleOutput
8
8 9
8 9 10
8 11 10
8 23 10
9 23 10
1 23 10
7
C++实现代码
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
using namespace std;
int main(int argc, char**argv)
{
int N, M;
vector< int > pages;
vector< int > frames;
//while(cin>>N>>M) // EOF end of file
{
cin>>N>>M;
for(int i=0; i<N; i++)
{
int tmp;
cin >> tmp;
pages.push_back(tmp);
}
int framesnum = 0, sum=0;
frames.clear();
frames.resize(M);
for(int i=0; i<N; i++)
{
vector< int >::iterator it = find(frames.begin(), frames.end(), pages[i]);
if (it!=frames.end())
{
// 不需要
}
else
{
if (framesnum < M)
{
frames[framesnum] = pages[i];
framesnum++;
copy(frames.begin(), frames.end(), ostream_iterator<int>(cout, " "));
cout << endl;
sum++;
}else if (framesnum == M)
{
//置换
int maxindex=-1;
vector< int >::iterator maxit = frames.begin();
for(vector< int >::iterator it=frames.begin();
it != frames.end(); it++)
{
vector< int >::iterator it2 = find(pages.begin()+i+1, pages.end(), *it);
if (it2!=pages.end() )
{
if (maxindex<(it2-pages.begin()))
{
maxindex = it2-pages.begin();
maxit = it;//候选置换页
}
}
else
{
maxit = it;
break;
}
}
*maxit = pages[i];
sum++;
copy(frames.begin(), frames.end(), ostream_iterator<int>(cout, " "));
cout << endl;
}
}
}
cout << sum << endl;
}
}
C#界面
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.IO.Pipes;
using System.Threading;
using System.Diagnostics;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string fileName = @"C:\\opt.exe";
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.FileName = fileName;
p.StartInfo.CreateNoWindow = true;
p.Start();
p.StandardInput.WriteLine(textBox1.Text + " " + textBox2.Text);
p.StandardInput.WriteLine(textBox3.Text );
p.WaitForExit();
string output = p.StandardOutput.ReadToEnd();
textBox4.Text = output;
}
}
}