Pagini recente » Cod sursa (job #2359261) | Cod sursa (job #956718) | Cod sursa (job #1585042) | Cod sursa (job #886932) | Cod sursa (job #2128775)
#include "stdio.h"
#include <algorithm>
#include <vector>
#include <stack>
#define MAX_N 100000
typedef struct data_s {
int best;
int index;
} data;
class Data {
public:
int best;
int index;
bool operator<(const Data& d) {
return this->best < d.best;
}
};
/* IO */
FILE *fin;
FILE *fout;
/* Problem Data */
int N;
int array[MAX_N];
// data bests[MAX_N];
// int best[MAX_N];
int predecesor[MAX_N];
int max_index, max_length;
std::vector<Data> b;
void read(void) {
fin = fopen("scmax.in", "r");
fscanf(fin, "%d", &N);
for (int i = 0; i < N; i++) {
fscanf(fin, "%d", &array[i]);
}
fclose(fin);
}
void write(void) {
int subsequence[max_length];
int index = max_index, nr = 0;
subsequence[nr++] = array[index];
while (predecesor[index] >= 0) {
subsequence[nr++] = array[predecesor[index]];
index = predecesor[index];
}
fout = fopen("scmax.out", "w");
fprintf(fout, "%d\n", max_length);
for (int i = nr - 1; i >= 0; i--) {
fprintf(fout, "%d ", subsequence[i]);
}
fclose(fout);
}
void solve(void) {
Data temp;
bool lone_wolf;
temp.best = 1;
temp.index = 0;
predecesor[0] = -1;
std::stack<Data> st;
b.push_back(temp);
std::make_heap(b.begin(), b.end());
for (int i = 1; i < N; i++) {
predecesor[i] = -1;
lone_wolf = false;
/*printf("==== i = %d =====\n", i);
for (std::vector<Data>::iterator it = b.begin(); it < b.end(); it++)
printf("Best: %d | Index: %d\n", it->best, it->index);
printf("\n");*/
while (array[b.front().index] > array[i]) {
temp = b.front();
std::pop_heap(b.begin(), b.end());
b.pop_back();
st.push(temp);
if (b.empty()) {
lone_wolf = true;
break;
}
}
if (lone_wolf) {
temp.best = 1;
temp.index = i;
b.push_back(temp);
std::push_heap(b.begin(), b.end());
while (!st.empty()) {
temp = st.top();
st.pop();
b.push_back(temp);
std::push_heap(b.begin(), b.end());
}
continue;
}
temp.best = 1 + b.front().best;
temp.index = i;
predecesor[i] = b.front().index;
b.push_back(temp);
std::push_heap(b.begin(), b.end());
while (!st.empty()) {
temp = st.top();
st.pop();
b.push_back(temp);
std::push_heap(b.begin(), b.end());
}
}
max_length = b.front().best;
max_index = b.front().index;
}
int main(void) {
read();
solve();
write();
return 0;
}