Pagini recente » Cod sursa (job #2356871) | Cod sursa (job #2418897) | Cod sursa (job #2228618) | Cod sursa (job #1296802) | Cod sursa (job #1387024)
#include<fstream>
#include<vector>
using namespace std;
ifstream fin( "interclasari.in" );
ofstream fout( "interclasari.out" );
const int kmax = 20;
int hn;
struct str{ int x, y; } h[ 2 * kmax + 1 ];
vector< int > v[ kmax + 1 ];
inline str mp( int x, int y ) {
str s; s.x = x; s.y = y; return s;
}
inline bool in_fata( int a, int b ) {
return ( v[ h[ a ].x ][ h[ a ].y ] < v[ h[ b ].x ][ h[ b ].y ] );
}
inline void heap_swap( int a, int b ) {
str aux = h[ a ]; h[ a ] = h[ b ]; h[ b ] = aux;
}
void urcare( int pos ) {
while ( pos > 1 && in_fata( pos, pos / 2 ) ) {
heap_swap( pos, pos / 2 );
pos /= 2;
}
}
void coborare( int pos ) {
int q;
bool ok = 1;
while ( (pos << 1) <= hn && ok == 1 ) {
q = (pos << 1);
if ( q + 1 <= hn && in_fata( q + 1, q ) ) {
++ q;
}
if ( in_fata( q, pos ) ) {
heap_swap( q, pos );
pos = q;
} else {
ok = 0;
}
}
}
void heap_insert( str x ) {
h[ ++ hn ] = x;
urcare( hn );
}
void heap_pop() {
heap_swap( 1, hn );
-- hn;
coborare( 1 );
}
int main() {
int k, x, y, ans;
fin >> k;
ans = 0;
hn = 0;
for( int i = 0; i < k; ++ i ) {
fin >> x;
ans += x;
for( int j = 0; j < x; ++ j ) {
fin >> y;
v[ i ].push_back( y );
}
if ( x > 0 ) {
heap_insert( mp( i, 0 ) );
}
}
fout << ans << "\n";
while ( hn > 0 ) {
x = h[ 1 ].x; y = h[ 1 ].y;
fout << v[ x ][ y ] << " ";
heap_pop();
if ( y + 1 < ( int )v[ x ].size() ) {
heap_insert( mp( x, y + 1 ) );
}
}
fout << "\n";
fin.close();
fout.close();
return 0;
}