Advertisement
sr_pope

P16249 - Task ordering

Jan 17th, 2019
386
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.02 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <queue>
  4. #include <algorithm>
  5. using namespace std;
  6.  
  7. int posicio(string w, const vector<string>& s, int esq, int dre) {
  8.   if (esq > dre) return -1;
  9.   else {
  10.     int i = (esq + dre)/2;
  11.     if (w < s[i]) return posicio(w,s,esq,i-1);
  12.     else if (w > s[i]) return posicio(w,s,i+1,dre);
  13.     else return i;
  14.   }
  15.  
  16. }
  17.  
  18. int index(const vector<string>& s, string w) {
  19.     return (posicio(w, s, 0, s.size()-1));
  20. }
  21.  
  22. void topological_sort(const vector<vector<int> >& g, vector<int>& pointers, const vector<string>& v1){
  23.     int n = g.size();
  24.     vector<int> end;
  25.     vector<int> visited(n,false);
  26.     priority_queue<int,vector<int>,greater<int> > q;
  27.     for(int i = 0; i < n; ++i){
  28.         if(pointers[i] == 0){
  29.             q.push(i);
  30.         }
  31.     }
  32.     if (q.empty()) cout << "NO VALID ORDERING" <<endl;
  33.       else{  
  34.         while(!q.empty()){
  35.             int u = q.top();
  36.             q.pop();
  37.             if(!visited[u]){
  38.                 end.push_back(u);
  39.                 visited[u] = true;
  40.                 for(int i = 0; i < g[u].size(); ++i){
  41.                     --pointers[g[u][i]];
  42.                     if (pointers[g[u][i]] == 0) q.push(g[u][i]);
  43.                 }
  44.             }
  45.         }
  46.         if (end.size() == n){
  47.             for(int i = 0; i < n; ++i){
  48.                 cout << v1[end[i]];
  49.             }
  50.             cout << endl;
  51.         }
  52.         else cout << "NO VALID ORDERING" <<endl;
  53.     }
  54. }
  55.  
  56. int main(){
  57.     int n,m;
  58.     while(cin >> n){
  59.         vector<string> v1(n);
  60.         for(int i = 0; i < n; ++i){
  61.             cin >> v1[i];
  62.         }
  63.         sort(v1.begin(),v1.end());
  64.         cin >> m;
  65.         vector<vector<int> > g(n);
  66.         vector<int> pointers(n,0);
  67.         for(int i = 0; i < m; ++i){
  68.             string s,h;
  69.             cin >> s >> h;
  70.             int u = index(v1,s);
  71.             int v = index(v1,h);
  72.             g[u].push_back(v);
  73.             ++pointers[v];
  74.         }
  75.         topological_sort(g,pointers, v1);
  76.     }
  77.        
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement