Pagini recente » Cod sursa (job #1197392) | Cod sursa (job #991781) | Cod sursa (job #1066697) | Cod sursa (job #1095495) | Cod sursa (job #2878809)
#include <bits/stdc++.h>
using namespace std;
ifstream f("text.in");
ofstream g("text.out");
typedef long long ll;
const int nmax = 3 + 1e6;
int n, kp, st[2 * nmax], dr[2 * nmax], af1[nmax];
ll vals[2 * nmax], result, af2[nmax];
queue<int> q1, q2;
int getnew();
void dfs(int, ll, int);
int32_t main()
{
f >> n;
kp = n;
for (int i = 1; i <= n; i++)
f >> vals[i], q1.push(i);
if (n == 1)
{
g << vals[1] << "\n1 1";
return 0;
}
int ax1 = q1.front();
q1.pop();
int ax2 = q1.front();
q1.pop();
vals[++kp] = vals[ax1] + vals[ax2];
st[kp] = ax1;
dr[kp] = ax2;
q2.push(kp);
while (q1.size() + q2.size() > 1)
{
ax1 = getnew();
ax2 = getnew();
vals[++kp] = vals[ax1] + vals[ax2];
st[kp] = ax1;
dr[kp] = ax2;
q2.push(kp);
}
dfs(kp, 0, 0);
g << result << '\n';
for (int i = 1; i <= n; i++)
g << af1[i] << " " << af2[i] << '\n';
return 0;
}
int getnew()
{
int rez;
if (q1.empty())
rez = q2.front(), q2.pop();
else if (q2.empty())
rez = q1.front(), q1.pop();
else if (vals[q1.front()] < vals[q2.front()])
rez = q1.front(), q1.pop();
else
rez = q2.front(), q2.pop();
return rez;
}
void dfs(int x, ll nr, int ct)
{
if (st[x] == 0 && dr[x] == 0)
result += 1ll * vals[x] * ct, af1[x] = ct, af2[x] = nr;
else
{
dfs(st[x], nr * 2, ct + 1);
dfs(dr[x], nr * 2 + 1, ct + 1);
}
}