例题6-21 系统依赖(System Dependencies, ACM/ICPC World Finals 1997, UVa506)
程序员文章站
2024-03-20 09:58:40
...
原题链接: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;
}
上一篇: js实现二分查找算法