被samlpe output 坑惨了啦……
samlpe output里面
REMOVE BROWSER
Removing BROWSER (echo)
Removing HTML
Removing TCPIP
对 这两行的顺序我一直搞不定 然后心想 难道要把遍历倒过来?当然不是 然而我还真这么干了。……
总之我就是按书上的思路敲了一遍 代码略有不同但是大体意思是一样的。捣鼓了半天实际上这是一个拓扑图我感觉。但是要用图的话可能链式结构会不考思维一点,但是逻辑感觉能爆炸。但其实从出入度角度也能写……明天或者今天晚上再看看。
看个吉尔!每次安装卸载整个图就会变动,出入度也会变,也就是说每次都要给他整一遍出度多少入度多少铁定超时呀。
诶 不对 每次安装的时候出入度+1卸载的时候出入度-1还是可以的呀……woc……
不会再研究了,出入度太蠢了,不管怎么想都觉得不如根据依赖关系来的爽快,实在是不愿意再想了,就这样过吧
#include<iostream>
#include<cstring>
#include<string>
#include<sstream>
#include<vector>
#include<algorithm>
#include<map>
using namespace std;
const int maxn = 10000;
int idx = 0;
map<int, string>id_name;
map<string, int>name_id;
vector<int>depend[maxn], depended[maxn];
vector<int>list;
int state[maxn];
int getid(string s)
{
if (name_id.count(s));
else
{
int id = idx;
name_id[s] = id;
id_name[id] = s;
idx++;
}
return name_id[s];
}
void install(int id, bool flag)
{
if (state[id] && flag)
{
cout << " " << id_name[id] << " is already installed." << endl;
return;
}
if (state[id])return;
int len = depend[id].size();
for (int i = 0; i < len; i++)
{
install(depend[id][i], false);
}
list.push_back(id);
state[id] = flag ? 1 : 2;
cout << " Installing " << id_name[id] << endl;
}
int remove(int id, bool flag)//1-- not install 2-- still needed 0-- everything ok removing
{
if (state[id] == 0)return 1;
int num = depended[id].size();
for (int i = 0; i < depended[id].size(); i++)
{
if (state[depended[id][i]] == 0)
num--;
}
if (num)return 2;
else if (num == 0)
{
state[id] = 0;
list.erase(find(list.begin(), list.end(), id));
cout << " Removing " << id_name[id] << endl;
//for (int i = depend[id].size() - 1; i >= 0; i--)
for(int i=0;i<depend[id].size();i++)
{
if(state[depend[id][i]]==2)
int res = remove(depend[id][i], false);
}
}
return 0;
}
void print()
{
//if (list.empty())cout << " just test" << endl;
for (int i = 0; i < list.size(); i++)
{
int id = list[i];
if (state[id])cout << " " << id_name[id] << endl;
}
}
int main()
{
//freopen("D:\\in.txt", "r", stdin);
//freopen("D:\\out.txt", "w", stdout);
string s;
memset(state, 0, sizeof(state));
while (getline(cin, s))
{
cout << s << endl;
stringstream ss(s);
string op;
ss >> op;
if (op == "DEPEND")
{
string item1, item2;
ss >> item1;
int id1 = getid(item1);
while (ss >> item2)
{
int id2 = getid(item2);
depend[id1].push_back(id2);
depended[id2].push_back(id1);
}
}
else if (op == "INSTALL")
{
string item;
ss >> item;
int id = getid(item);
install(id, true);
}
else if (op == "REMOVE")
{
string item;
ss >> item;
int id = getid(item);
int result = remove(id, true);
if (result == 1)
cout << " " << id_name[id] << " is not installed." << endl;
else if (result == 2)
cout << " " << id_name[id] << " is still needed." << endl;
//else if(result==0)
}
else if (op == "LIST")
{
print();
}
else if (op == "END")
{
break;
}
}
//fclose(stdin);
//fclose(stdout);
return 0;
}