UVa 506 - System Dependencies <图的拓扑序+STL应用>
这道题仍然是两个月之前做过,当时是RE,但不知为何当时没有考虑到把数组开的大一点就可以了。今天拿出代码将1024改为102400,瞬间AC。
网上搜了下竟然没有这个题的题解。我的做法还是很普通的做法,就是使用了STL的几个工具而已,比如vector、string、erase、remove、stringstream等等,没有算法上的难度。
#include <bits/stdc++.h> #define maxn 102400 using namespace std; int cnt = 0, status[maxn]; vector<int> depend[maxn], depend2[maxn]; vector<int> installed; string name[maxn]; int get_id(const string & x) { for (int i = 0; i < cnt; i++) if (name[i] == x) return i; name[cnt++] = x; return cnt-1; } void instal(int item, bool top) { if (!status[item]){ for (size_t i = 0; i < depend[item].size(); i++) instal(depend[item][i], false); cout << " Installing " << name[item] << endl; status[item] = top ? 1 : 2; installed.push_back(item); } else if(top) cout << " " << name[item] << " is already installed." << endl; } bool needed(int item) { for (size_t i = 0; i < depend2[item].size(); i++) if (status[depend2[item][i]]) return true; return false; } void Remove(int item, bool top) { if(top && status[item]==0) cout << " " << name[item] << " is not installed." << endl; else if(top && needed(item)) cout << " " << name[item] << " is still needed." << endl; else if ((top || status[item] == 2) && !needed(item)){ status[item] = 0; installed.erase(remove(installed.begin(), installed.end(), item), installed.end()); cout << " Removing " << name[item] << endl; for (size_t i = 0; i < depend[item].size(); i++) Remove(depend[item][i], false); } } int main() { //freopen("in.txt", "r", stdin); ios::sync_with_stdio(false); string line; while (getline(cin, line), line != "END") { cout << line << endl; stringstream ss(line); if (line[0] == 'L'){ for (size_t i = 0; i != installed.size(); ++i) cout << " " << name[installed[i]] << endl; } else{ string t1, t2, t3; ss >> t1 >> t2; if (t1[0] == 'D'){ while (ss >> t3){ depend[get_id(t2)].push_back(get_id(t3)); depend2[get_id(t3)].push_back(get_id(t2)); } } else if (t1[0] == 'I') instal(get_id(t2), true); else if (t1[0] == 'R') Remove(get_id(t2), true); } } cout << "END" << endl; return 0; }