Pagini recente » Cod sursa (job #995166) | Cod sursa (job #624894) | Cod sursa (job #88321) | Cod sursa (job #1233325) | Cod sursa (job #2500539)
#include<bits/stdc++.h>
using namespace std;
ifstream fin("huffman.in");
ofstream fout("huffman.out");
const long long INF = (1LL<<62);
const int DIM = 1e6 + 3;
long long arr[DIM * 2];
int N, pos, p, last;
long long sol;
pair<int,long long> ans[DIM];
int st[2 * DIM], dr[2 * DIM];
void dfs( int nod, int lg, long long cod ){
if( 1 <= nod && nod <= N ){
ans[nod].first = lg;
ans[nod].second = cod;
}
if( st[nod] == 0 )
return;
dfs( st[nod], lg + 1, cod * 2 );
dfs( dr[nod], lg + 1, cod * 2 + 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++ ){
long long 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, 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;
}