Cod sursa(job #772666)

Utilizator dm1sevenDan Marius dm1seven Data 30 iulie 2012 14:11:15
Problema Potrivirea sirurilor Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.85 kb
#include <iostream>
#include <fstream>
#include <string>
#include <list>
#include <utility>
using namespace std;

//int e_005_strmatch()
int main()
{
	string in_file = "strmatch.in";
	string out_file = "strmatch.out";
	
	const int enought_matches = 1000;

	string u, v;

	ifstream ifs(in_file.c_str());
	ifs>>u>>v;
	ifs.close();

	typedef pair<int, int> match_type;

	list<match_type> matches;//pair(start_position of u in v, end_position match in v)
	list<int> complete_matches;	
	if (u.size() <= v.size())
	{
		//processing
		unsigned int i = 0;
		while (i < v.size())
		{		
			//update the matching list
			list<match_type>::iterator it = matches.begin();
			while ( it != matches.end() )
			{
				pair<int, int>& p = *it;			
				int& end_pos_in_u = p.second;
				
				bool erased = false;
				//assumes u.size() >= 2
				if (u[end_pos_in_u + 1] == v[i]) end_pos_in_u++;
				else 
				{
					it = matches.erase(it);
					erased = true;
				}
				
				if (end_pos_in_u + 1 == (int) u.size())//complete match
				{
					//move the information to the complete_matches list
					complete_matches.push_back(p.first);					
					
					//remove from the temporary matching list
					it = matches.erase(it);
					erased = true;
				}

				//otherwise it gets incompatible or not incrementable iterators
				if (!erased) it++;				
			}
			
			//assumes u.size() >= 2
			if (u[0] == v[i]) //add a new entry into the matching list
			{
				matches.push_back(make_pair(i, 0));
			}

			i++;
		}
	}
	
	ofstream ofs(out_file.c_str());
	ofs<<complete_matches.size()<<"\n";
	int how_many_matches;
	list<int>::iterator it;
	for (it = complete_matches.begin(), how_many_matches = 1;
		it != complete_matches.end() && how_many_matches <= enought_matches; 
		it++, how_many_matches++)
		ofs<<*it<<" ";
	ofs.close();

	return 0;
}