(操作系统)C++ 首次适应分配算法

【问题描述】给出某系统中的进程请求表和空闲分配表,系统采用可变分区分配策略。

请采用首次适应算法来处理这些进程序列的请求,分别打印出分区分配前后的空闲分区表以及分配过程。

【输入形式】
【输出形式】
【样例输入】

第一行为空闲分区数目n

接下来n行为空闲分区表(格式同上图一致)

第n+1为请求进程数目m

最后m行尾进程请求表(格式同上图一致)
【样例输出】(

说明:

1. 第1组数据为初始空闲表,第2组数据为按照给定算法进行排序后的空闲分区表,最后一组数据为分配后的分区表,中间为分配过程。

2. 每组数据中,每列两个数字之间用一个空格分开。

3. 如果没有分区满足要求,则输出:“Process * no partition.”

4. 分配后的空闲表输出时,不输入大小为0的分区。

1       32      100

2       10      150

3       5       200

4       218     220

5       96      530

1       32      100

2       10      150

3       5       200

4       218     220

5       96      530

Process A use * partition.

Process B use * partition.

Process C use * partition.

1       27      105

2       10      150

3       5       200

4       78      360

5       96      530

代码实现:

#include <iostream>
#include <algorithm>
#include <string>
#include <fstream>

using namespace std;

const int N = 100;

class Partition
{
public:
	int size;
	int begin;
	int num;
	Partition()
	{
		size=0;
		begin=0;
		num=0;
	}
	void SetPartition(int s,int b,int n)
	{
		size=s;
		begin=b;
		num=n;
	}
	void Display()
	{
		cout<<num<<" "<<size<<" "<<begin<<endl;
	}	
}; 

class Process
{
public:
	string name;
	int need;
	bool isfinish;
	Process()
	{
		need=0;
		isfinish=false;
	}	
	void SetProcess(string na,int ne)
	{
		name=na;
		need=ne;
	}
};

bool Compare(Partition& a,Partition& b)
{
	return a.begin<b.begin;
}

void FirstFit(Partition MP[],Process Pro[],int n,int m)
{
	for(int i=0;i<m;i++)
	{
		for(int j=0;j<n;j++)
		{
			if(MP[j].size>=Pro[i].need)
			{
				MP[j].size-=Pro[i].need;
				MP[j].begin+=Pro[i].need;
				Pro[i].isfinish=true;
				cout<<"Process "<<Pro[i].name<<" use "<<MP[j].num<<" partition."<<endl;
				break;
			}
		}
		sort(MP,MP+n,Compare);
	}
	for(int i=0;i<m;i++)
	{
		if(Pro[i].isfinish==false) cout<<"Process "<<Pro[i].name<<" no partition."<<endl;
	}
    cout<<endl;
}

int main()
{
	Partition MP[N];
	Process Pro[N];
	fstream of;
	of.open("test.txt",ios::in);
	int n;
	of>>n;
	for(int i=0;i<n;i++)
	{
		int size;
		int begin;
		int num;
		of>>num>>size>>begin;
		MP[i].SetPartition(size,begin,num);
	}
	int m;
    of>>m;
	for(int i=0;i<m;i++)
	{
		string name;
		int need;
		of>>name>>need;
		Pro[i].SetProcess(name,need);
	}
	for(int i=0;i<n;i++) MP[i].Display();
    cout<<endl;
	sort(MP,MP+n,Compare);
	for(int i=0;i<n;i++) MP[i].Display();
	FirstFit(MP,Pro,n,m);
	for(int i=0;i<n;i++) 
    {
        if(MP[i].size!=0) MP[i].Display();
    }
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值