这道题有点郁闷,有没有坑取决于你是怎么输入的。。。
题目有些地方没说,如果想当然就会WA。。
要注意: 1.在depend里没出现的组件名字,在安装或删除里都可能出现。。也就是说在这时,也不要忘了记录新名字。
2.显示安装只能显示删除。
3.除了list里要按照安装的顺序输出,其他输出没有顺序问题。
#include<bits/stdc++.h>
using namespace std;
const int maxn=9000;
vector<int> depend[maxn],depend2[maxn],installed;
map<string,int>p;
int status[maxn];
string name[maxn];
void install(int item,bool toplevel) {
if(!status[item]) {
for(int i=0;i<depend[item].size();i++)
install(depend[item][i],false);
cout<<" Installing "<<name[item]<<"\n";
status[item] = toplevel ? 1: 2;
installed.push_back(item);
}
}
bool needed(int item) {
for(int i=0;i<depend2[item].size();i++)
if(status[depend2[item][i]]) return true;
return false;
}
void removed(int item,bool toplevel) {
if((toplevel||status[item]==2)&&!needed(item)) {
status[item] = 0;
installed.erase(remove(installed.begin(), installed.end(), item), installed.end());
cout<<" Removing "<<name[item]<<"\n";
for(int i=0;i<depend[item].size();i++)
removed(depend[item][i],false);
}
}
int main() {
string buf; int cnt=1;
memset(status,0,sizeof(status));
while(getline(cin,buf)) {
cout<<buf<<'\n';
stringstream ss(buf);
if(buf[0]=='E') break;
else if(buf[0]=='L') {
for(int i=0;i<installed.size();i++)
cout<<" "<<name[installed[i]]<<"\n";
}
else {
string s1,s2,s3;
ss>>s1>>s2;
if(s1[0]=='D') {
int x;
if(!p.count(s2)) { p[s2]=cnt; name[cnt]=s2; x=cnt;cnt++; }
else x=p[s2];
while(ss>>s3) {
if(!p.count(s3)) {
p[s3]=cnt; name[cnt]=s3;
depend[x].push_back(cnt);
depend2[cnt].push_back(x);cnt++;
}
else { int y=p[s3]; depend[x].push_back(y);depend2[y].push_back(x); }
}
}
if(buf[0]=='I') {
if(!p.count(s2)) { p[s2]=cnt; name[cnt]=s2; cnt++; }
if(status[p[s2]]) cout<<" "<<s2<<" is already installed.\n";
else install(p[s2],true);
}
if(buf[0]=='R') {
int t;
if(!p.count(s2)) { p[s2]=cnt; t=p[s2]; name[cnt]=s2; cnt++;}
else t=p[s2];
if(!status[t]) cout<<" "<<name[t]<<" is not installed.\n";
else if(needed(t)) cout<<" "<<name[t]<<" is still needed.\n";
else removed(t,true);
}
}
}
return 0;
}