Cod sursa(job #763394)

Utilizator danalex97Dan H Alexandru danalex97 Data 2 iulie 2012 09:57:24
Problema Gropi Scor 50
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.33 kb
#include <fstream>
#include <algorithm>
using namespace std;

ifstream F("gropi.in");
ofstream G("gropi.out");

typedef pair<int,int> Pair;

#define Ng 100011
#define col first 
#define lin second 
#define swap(a,b) ( a ^= b ^= a ^= b )

int N,M,Q;
Pair Gropi[Ng];
Pair Start,End;
 
int Find_next(int Val,int St,int Dr)
{
	if ( St==Dr ) return St;
	if ( Dr-St==1 )
	{
		if ( Gropi[St].col > Val ) return St;
		return Dr;
	}
	
	int Mid=(St+Dr) /2;
	if ( Gropi[Mid].col > Val )
		return Find_next(Val,St,Mid);
	else
		return Find_next(Val,Mid+1,Dr);
}

int main()
{
	F>>N>>M;
	for (int i=1;i<=M;++i)
		F>>Gropi[i].lin>>Gropi[i].col;
	sort(Gropi,Gropi+M+1);
	
	for (F>>Q;Q;--Q)
	{
		F>>Start.lin>>Start.col;
		F>>End.lin>>End.col;
		if ( Start==End ) 
		{
			G<<"1\n";
			continue;
		}
		if ( Start.col == End.col )
		{
			G<<"2\n";
			continue;
		}			
		if ( Start.col > End.col )
		{
			swap(Start.col,End.col);
			swap(Start.lin,End.lin);
		}			
		
		int Poz=Find_next(Start.col,1,M);
		int Co=1;
		
		while ( Gropi[Poz].col < End.col && Poz<=M )
		{
			if ( Gropi[Poz].lin == Start.lin )
			{
				Start.lin=3-Start.lin;
				++Co;
			}
			
			Co+=Gropi[Poz].col - Start.col;
			Start.col=Gropi[Poz++].col;
		}
		Co+=End.col - Start.col + ( End.lin != Start.lin );
		
		G<<Co<<'\n';
	}
}