现在的位置: 首页 > 综合 > 正文

银行家算法的简单实现

2013年09月05日 ⁄ 综合 ⁄ 共 1982字 ⁄ 字号 评论关闭


#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <queue>
#include <algorithm>
#include <vector>
#include <cstring>
#include <stack>
#include <cctype>
#include <utility>
#include <map>
#include <string>
#include <climits> 
#include <set>
#include <string> 
#include <sstream>
#include <utility>
#include <ctime>
//#pragma comment(linker, "/STACK:1024000000,1024000000") 

using std::priority_queue;
using std::vector;
using std::swap;
using std::stack;
using std::sort;
using std::max;
using std::min;
using std::pair;
using std::map;
using std::string;
using std::cin;
using std::cout;
using std::set;
using std::queue;
using std::string;
using std::istringstream;
using std::getline;
using std::make_pair;
using std::greater;

const int MAXN(30);
const int MAXP(30);

int Ava[MAXN];
int Max[MAXP][MAXN], All[MAXP][MAXN], Nee[MAXP][MAXN];
int tava[MAXN];
int tall[MAXP][MAXN], tnee[MAXP][MAXN];
int Req[MAXN];
bool finish[MAXP];

int n, p;

bool is_legal(int num)
{
	for(int i = 1; i <= n; ++i)
		if(tnee[num][i] > tava[i])
			return false;
	return true;
}

bool dfs(int dep)
{
	if(dep == p)
		return true;
	for(int i = 1; i <= p; ++i)
		if(!finish[i] && is_legal(i))
		{
			finish[i] = true;
			for(int j = 1; j <= n; ++j)
				tava[j] += tall[i][j];
			if(dfs(dep+1))
				return true;
			for(int j = 1; j <= n; ++j)
				tava[j] -= tall[i][j];
			finish[i] = false;
		}
	return false;
}

int main()
{
	int num;
	while(~scanf("%d%d", &n, &p)) //资源数  进程数
	{
		for(int i = 1; i <= p; ++i)
			for(int j = 1; j <= n; ++j)
				scanf("%d", Max[i]+j);
		for(int i = 1; i <= p; ++i)
			for(int j = 1; j <= n; ++j)
				scanf("%d", All[i]+j);
		for(int i = 1; i <= p; ++i)
			for(int j = 1; j <= n; ++j)
				scanf("%d", Nee[i]+j);
		for(int i = 1; i <= n; ++i)
			scanf("%d", Ava+i);
		while(~scanf("%d", &num))
		{
			for(int i = 1; i <= n; ++i)
				scanf("%d", Req+i);
			bool flag = false;
			for(int i = 1; i <= n; ++i)
				if(Req[i] > Nee[num][i] || Req[i] > Ava[i])
				{
					printf("申请非法\n");
					flag = true;
					break;
				}
			if(flag)
				continue;
			memcpy(tava, Ava, sizeof(tava));
			memcpy(tall, All, sizeof(tall));
			memcpy(tnee, Nee, sizeof(tnee));
			memset(finish, 0, sizeof(finish));
			for(int i = 1; i <= n; ++i)
			{
				tava[i] -= Req[i];
				tall[num][i] += Req[i];
				tnee[num][i] -= Req[i];
			}
			if(dfs(0))
			{
				printf("安全分配\n");
				for(int i = 1; i <= n; ++i)
				{
					Ava[i] -= Req[i];
					All[num][i] += Req[i];
					Nee[num][i] -= Req[i];
				}
			}
			else
				printf("不安全分配\n");
		}
	}
}

抱歉!评论已关闭.