例题6-21 系统依赖(System Dependencies, ACM/ICPC World Finals 1997, UVa506)

原题链接:https://vjudge.net/problem/UVA-506
分类:图
备注:中级模拟,拓扑序

注意:在安装和删除的时候,依赖的依赖也要考虑进来。LIST的输出顺序是安装顺序。如果依赖由隐式(间接)安装变成了显式(直接)安装,即对该依赖出现了INSTALL语句,则REMOVE语句未对其直接作用时,不可删除该依赖。

代码如下:

#include<iostream>
#include<algorithm>
#include<sstream>
#include<vector>
#include<string>
#include<map>
#include<set>
using namespace std;
typedef long long ll;
const ll inf = 9223372036854775806;
string line, x, y;
map<string, vector<string> >depend, depend2;
map<string, int>status;
map<string, ll>ranking;
set<string>vis;
vector<string>hav;
ll cnt;
bool cmp(const string& a, const string& b) {
	return ranking[a] < ranking[b];
}
void install(const string& t) {
	for (int i = 0; i < depend[t].size(); i++)
		if (!status[depend[t][i]])install(depend[t][i]);
	cout << "   Installing " << t << endl;
	status[t] = 2; ranking[t] = cnt++;
}
void remove(const string& t) {
	cout << "   Removing " << t << endl;
	status[t] = 0; ranking[t] = inf;
	for (int i = 0; i < depend[t].size(); i++) {
		string u = depend[t][i];
		if (status[u] != 2)continue;
		bool isRmoved = true;
		for (int j = 0; j < depend2[u].size(); j++) 
			if (status[depend2[u][j]]) { isRmoved = false; break; }
		if (isRmoved) remove(u);
	}
}
int main(void) {
	while (getline(cin, line)) {
		cout << line << endl;
		stringstream kk(line);
		kk >> x;
		if (x[0] == 'D') {
			kk >> x;
			if (!vis.count(x)) { vis.insert(x); hav.push_back(x); ranking[x] = inf; }
			while (kk >> y) {
				depend[x].push_back(y);//x依赖y
				depend2[y].push_back(x);//y被x所依赖
				if (!vis.count(y)) { vis.insert(y); hav.push_back(y); ranking[y] = inf; }
			}
		}
		else if (x[0] == 'I') {
			kk >> x;
			if (status[x] > 0) { cout << "   " << x << " is already installed." << endl; continue; }
			if (!vis.count(x)) { vis.insert(x); hav.push_back(x); ranking[x] = inf; }
			install(x); status[x] = 1;
		}
		else if (x[0] == 'R') {
			kk >> x;
			if (status[x] == 0) { cout << "   " << x << " is not installed." << endl; continue; }
			bool isRmoved = true;
			for (int i = 0; i < depend2[x].size(); i++)
				if (status[depend2[x][i]]) { isRmoved = false; break; }
			if (!isRmoved) { cout << "   " << x << " is still needed." << endl; continue; }
			remove(x);
		}
		else if (x[0] == 'L') {
			sort(hav.begin(), hav.end(), cmp);
			for (int i = 0; i < hav.size(); i++) {
				if (ranking[hav[i]] == inf)break;
				cout << "   " << hav[i] << endl;
			}
		}
		else {
			while (!hav.empty())hav.pop_back();
			cnt = 0;vis.clear();status.clear();
			ranking.clear();depend.clear(); depend2.clear();
		}
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JILIN.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值