Pagini recente » Cod sursa (job #2017818) | Monitorul de evaluare | Cod sursa (job #2328375) | Cod sursa (job #314025) | Cod sursa (job #2062384)
#include <fstream>
#include <queue>
#include <cmath>
using namespace std;
ifstream cin ("huffman.in");
ofstream cout ("huffman.out");
class cmp{
public:
bool operator() (pair<long long , int> a , pair<long long , int> b){
return a.first > b.first;
}
};
pair<int , int> node[2000100];
pair<int , long long> ans[1000100];
priority_queue <pair<long long , int> , vector<pair<long long , int>> , cmp> Q;
queue <pair<int ,pair<int, long long>>> q;
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
int n;
cin>>n;
for (int i=1; i<=n; i++){
int nr;
cin>>nr;
Q.push({nr , i});
}
int cont = 0;
int nod = n;
while (Q.size() > 1){
pair<long long , int> st , dr;
st.first = Q.top().first;
st.second = Q.top().second;
Q.pop();
dr.first = Q.top().first;
dr.second = Q.top().second;
Q.pop();
nod++;
node[nod].first = st.second;
node[nod].second = dr.second;
Q.push({st.first + dr.first , nod});
cont += st.first + dr.first;
}
cout<<cont<<'\n';
q.push({Q.top().second , {0 , 0}});
while (!q.empty()){
pair<int ,pair<int , long long>> now;
now.first = q.front().first;
now.second.first = q.front().second.first;
now.second.second = q.front().second.second;
q.pop();
if (node[now.first].first == 0){
ans[now.first].first = now.second.first;
ans[now.first].second = now.second.second;
continue;
}
q.push({node[now.first].first , {now.second.first + 1 , now.second.second << 1LL}});
q.push({node[now.first].second , {now.second.first + 1 , (now.second.second << 1LL) + 1LL}});
}
for (int i=1; i<=n; i++){
cout<<ans[i].first<<" "<<ans[i].second<<'\n';
}
return 0;
}