Pagini recente » Cod sursa (job #2667620) | Cod sursa (job #1510780) | Cod sursa (job #2713684) | Cod sursa (job #2310220) | Cod sursa (job #1129609)
#include <iostream>
#include <fstream>
using namespace std;
#define INFINITY 1e20
void PrintSequence(int v[100001], int S[100001], int val, int poz);
ofstream g("scmax.out");
int main()
{
/**
* Read the numbers from `scmax.in`.
*/
ifstream f("scmax.in");
int v[100001];
int n; // The length of numbers array.
f >> n;
for (int i = 0; i < n; i++)
f >> v[i];
f.close();
/**
* Solve the problem using dynamic programming.
*/
// Declare an array in which we will save our partial results for
// every step. Initialize it with a big number (INFINITY).
int S[100001];
for (int i = 0; i < n; i++)
S[i] = INFINITY;
// The solution for the first step is the first number itself.
// So, the length of the longest non-decreasing sequence is 1;
S[0] = 1;
// Iterate over all items of our array of numbers (v), except the first one
// for which we have already calculated the result.
for (int i = 1; i < n; i++)
{
S[i] = 1;
// Iterate over elements less than `i` and check if v[i] is a valid solution
// for any previous sequences.
for (int j = 0; j < i; j++)
if(v[j] < v[i] && S[j] + 1 > S[i])
S[i] = S[j] + 1;
}
/**
* Print the length of the longest non-decreasing sequence
* in `scmax.out'.
*/
int max = 0;
int poz = 0;
for (int i = 0; i < n; i++)
if (S[i] > max)
{
max = S[i];
poz = i;
}
g << max << '\n';
/**
* Print the non-decreasing sequence.
*/
PrintSequence(v, S, max, poz);
return 0;
}
void PrintSequence(int v[100001], int S[100001], int val, int poz)
{
for (int i = poz - 1; i >= 0; i--)
if (S[i] + 1 == val && v[i] < v[poz])
{
PrintSequence(v, S, val - 1, i);
break;
}
g << v[poz] << " ";
}