[ create a new paste ] login | about

Link: http://codepad.org/WyaDDkuS    [ raw code | output | fork ]

C++, pasted on Apr 29:
#include <iostream>
#include <iterator>
#include <locale>

#include <algorithm>
#include <functional>

template <typename I, typename U>
void find_longest(I begin, I end, U u)
{
	typedef typename std::iterator_traits<I>::difference_type difference_type;

	I next, first = begin, found = end;
	difference_type max_seq = 0;

	for ( ; (next = std::adjacent_find(begin, end, u)) != end; begin = ++next)
	{
		const difference_type curr_length = std::distance(begin, next) + 1;
		if (curr_length > max_seq)
		{ max_seq = curr_length; found = begin; }
	}

	const difference_type last_length = std::distance(begin, next);
	if (last_length > max_seq)
	{ max_seq = last_length; found = begin; }

	typedef typename std::iterator_traits<I>::value_type T;
	typedef std::ostream_iterator<T> O;

	std::cout << "Исходная последовательность:" << std::endl;
	std::copy(first, end, O(std::cout, " "));
	std::cout << std::endl;

	std::cout << "Самая длинная последовательность:" << std::endl;
	std::copy(found, found + max_seq, O(std::cout, " "));
	std::cout << std::endl;
}

struct R
{
	static const int Min = -3;
	static const int Max = 3;

	int operator()() const
	{
		return rand() % (Max - Min + 1) + Min;
	}
};

int main()
{
	setlocale(LC_ALL, "");
	srand((unsigned) time(NULL));

	int arr[30];
	std::generate_n(arr, sizeof(arr) / sizeof(arr[0]), R());

	find_longest(arr, arr + sizeof(arr) / sizeof(arr[0]), std::not2(std::equal_to<int>()));
	
	return 0;
}


Output:
1
2
3
4
Исходная последовательность:
2 -2 1 0 -3 -1 3 -3 1 1 1 -3 -1 2 0 -3 -3 3 2 -1 -2 1 3 -1 2 1 -1 1 3 1 
Самая длинная последовательность:
1 1 1 


Create a new paste based on this one


Comments: