Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<iostream>
- #include<fstream>
- #include<vector>
- #include<queue>
- #include<algorithm>
- #include<functional>
- using namespace std;
- #define INF 999
- #define max_size 10000
- vector<int> g[max_size];
- int n,m;
- vector<pair<int,int>> aux; //keeps the rank and parent so it can be accessed
- //easier than from the queue
- vector<int> prufer_code;
- priority_queue < pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> q;
- vector<pair<int,int>> edges;
- vector<int> code;
- void read()
- {
- ifstream in("code_file.txt");
- if (in.is_open())
- {
- in >> n >> m;
- int x, y, w;
- aux.assign(n+1,{0,-1}); //second is the parent
- for (int i = 0; i<m; i++)
- {
- in >> x >> y;
- aux[x].first++;
- aux[x].second=y;
- aux[y].first++;
- aux[y].second=x;
- }
- for(int i=1;i<aux.size();i++)
- q.push(aux[i]);
- }
- else
- cout << "Unable to open the file\n";
- }
- void decrease_rank(int parent)
- {
- deque<pair<int, int>> deq;
- pair<int, int> pp;
- while (!q.empty())
- {
- pp = q.top();
- q.pop();
- deq.push_back(pp);
- }
- for (deque<pair<int, int>>::iterator it = deq.begin(); it != deq.end(); ++it)
- if ((*it).second == parent)
- {
- (*it).first--;
- break;
- }
- for (deque<pair<int, int>>::iterator it = deq.begin(); it != deq.end(); ++it)
- q.push(*it);
- }
- void prufer_code_()
- {
- while (!q.empty())
- {
- pair<int, int> p = q.top();
- decrease_rank(p.second);
- q.pop();
- prufer_code.push_back(p.second);
- }
- prufer_code.erase(prufer_code.end()-1);
- prufer_code.erase(prufer_code.end()-1);
- }
- int find_minimum(vector<int> code)
- {
- int minimum=1;
- while(find(code.begin(),code.end(),minimum)!=code.end())
- minimum++;
- return minimum;
- }
- void prufer_decode_()
- {
- int u,v;
- int i=0;
- while(i<code.size()+1)
- {
- u=code[0];
- v=find_minimum(code);
- cout<<"minimum:"<<v<<endl;
- if(i!=code.size())
- {
- code.erase(code.begin());
- code.push_back(v);
- edges.push_back({u,v});
- }
- i++;
- }
- u=find_minimum(code);
- code.push_back(u);
- v=find_minimum(code);
- edges.push_back({u,v});
- }
- int main()
- {
- read();
- prufer_code_();
- cout<<"prufer code:";
- for(int i=0;i<prufer_code.size();i++)
- cout<<prufer_code[i]<<" ";
- cout<<endl;
- code.push_back(1);
- code.push_back(1);
- code.push_back(5);
- prufer_decode_();
- cout<<"the egdes:\n";
- for(int i=0;i<edges.size();i++)
- cout<<edges[i].first<<"-"<<edges[i].second<<endl;
- return 0;
- }
Add Comment
Please, Sign In to add comment