Pagini recente » Cod sursa (job #1635009) | Cod sursa (job #376695) | Monitorul de evaluare | Cod sursa (job #387360) | Cod sursa (job #3259009)
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
void scmax_from_file() {
// Open input file
ifstream infile("scmax.in");
int n;
infile >> n;
vector<int> subsir(n);
for (int i = 0; i < n; ++i) {
infile >> subsir[i];
}
infile.close();
// `dp` array to store indices of the smallest ending elements
vector<int> dp;
vector<int> prev(n, -1); // To store predecessors for reconstruction
// Process the sequence
for (int i = 0; i < n; ++i) {
// Find the position to replace using binary search
auto it = lower_bound(dp.begin(), dp.end(), subsir[i], [&](int idx, int value) {
return subsir[idx] < value;
});
int pos = it - dp.begin();
if (it != dp.end()) {
dp[pos] = i; // Replace existing value
} else {
dp.push_back(i); // Append new value
}
// Update predecessor information
if (pos > 0) {
prev[i] = dp[pos - 1];
}
}
// Reconstruct the LIS
vector<int> sequence;
for (int i = dp.back(); i >= 0; i = prev[i]) {
sequence.push_back(subsir[i]);
}
reverse(sequence.begin(), sequence.end());
// Write the output to "scmax.out"
ofstream outfile("scmax.out");
outfile << dp.size() << "\n"; // Length of LIS
for (size_t i = 0; i < sequence.size(); ++i) {
if (i > 0) outfile << " ";
outfile << sequence[i];
}
outfile << "\n";
outfile.close();
}
int main() {
scmax_from_file();
return 0;
}