Pagini recente » Cod sursa (job #15445) | Cod sursa (job #114418) | Cod sursa (job #724850) | Cod sursa (job #2213963) | Cod sursa (job #2500514)
#include<bits/stdc++.h>
using namespace std;
ifstream fin("huffman.in");
ofstream fout("huffman.out");
const int INF = 0x3f3f3f3f;
const int DIM = 1e6 + 5;
int arr[DIM * 2 + 5];
int N, pos, p, last;
long long sol;
pair<int,long long> ans[DIM * 2];
int st[2 * DIM], dr[2 * DIM];
void dfs( int nod, int lg ){
ans[nod].first = lg;
long long aux = ans[nod].second;
if( nod > N )
sol += arr[nod];
if( st[nod] == 0 )
return;
ans[ st[nod] ].second = aux * 2;
ans[ dr[nod] ].second = aux * 2 + 1;
dfs( st[nod], lg + 1 );
dfs( dr[nod], lg + 1 );
return;
}
int main(){
fin >> N;
for( int i = 1; i <= N; i++ )
fin >> arr[i];
pos = N + 1;
last = N;
p = 1;
for( int step = 1; step < N; step++ ){
int s1 = INF, s2 = INF, s3 = INF;
if( p + 1 <= N )
s1 = arr[p] + arr[p + 1];
if( pos <= last && p <= N )
s2 = arr[p] + arr[pos];
if( pos + 1 <= last )
s3 = arr[pos] + arr[pos + 1];
if( s1 <= s2 && s1 <= s3 ){
last++;
st[last] = p;
dr[last] = p + 1;
arr[last] = s1;
p += 2;
continue;
}
if( s2 <= s3 && s2 <= s1 ){
last++;
st[last] = p;
dr[last] = pos;
arr[last] = s2;
pos++;
p++;
continue;
}
if( s3 <= s1 && s3 <= s2 ){
last++;
st[last] = pos;
dr[last] = pos + 1;
arr[last] = s3;
pos += 2;
continue;
}
}
dfs( last, 0 );
/*
for( int i = 1; i <= N; i++ )
sol += 1LL * arr[i] * ans[i].first;
*/
fout << sol << "\n";
for( int i = 1; i <= N; i++ )
fout << ans[i].first << " " << ans[i].second << "\n";
return 0;
}