Cod sursa(job #239588)

Utilizator SleepyOverlordPatcas Csaba SleepyOverlord Data 5 ianuarie 2009 00:00:52
Problema Gropi Scor 20
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.14 kb
#include <stdio.h>
#include <ctype.h>
#include <vector>
#include <algorithm>

using namespace std;

int c,n,m,ind;
char buf[50];
vector <pair<int,int> > gropi(100000), gropi2;

int getn()
{
	int ans=0;
	while (isdigit(buf[ind]))
	{
		ans=ans*10+buf[ind]-'0';
		++ind;
	}
	++ind;
	return ans;
}

int main()
{
	FILE* fin=fopen("gropi.in","r");
	FILE* fout=fopen("gropi.out","w");
	fscanf(fin,"%d%d\n",&c,&n);
	for (int q=0;q<n;++q)
	{
		fgets(buf,50,fin);
		ind=0;
		int x=getn(), y=getn();
		gropi[q]=make_pair(y,x);
	}
	sort(gropi.begin(),gropi.begin()+n);

	gropi2.push_back(gropi[0]);
	for (int q=1;q<n;++q)
		if (gropi[q].second!=gropi[q-1].second) gropi2.push_back(gropi[q]);

	fscanf(fin,"%d\n",&m);
	for (int q=0;q<m;++q)
	{
		fgets(buf,50,fin);
		ind=0;
		int x1=getn(), y1=getn(), x2=getn(), y2=getn(), ans=abs(y2-y1)+1,i,j,i1,j1;

		if (y1>y2)
		{
			swap(x1,x2);
			swap(y1,y2);
		}

		i=upper_bound(gropi2.begin(),gropi2.end(),make_pair(y1,x1))-gropi2.begin();
		while(i<gropi2.size() && gropi2[i].first<=y1) ++i;

		i1=upper_bound(gropi.begin(),gropi.begin()+n,make_pair(y1,x1))-gropi.begin();
		while(i1<gropi.size() && gropi[i1].first<=y1) ++i;
		
		j=lower_bound(gropi2.begin(),gropi2.end(),make_pair(y2,x2))-gropi2.begin();
		while(j==gropi2.size() || j>=0 && gropi2[j].first>=y2) --j;

		j1=lower_bound(gropi.begin(),gropi.begin()+n,make_pair(y2,x2))-gropi.begin();
		while(j1==n || j1>=0 && gropi[j1].first>=y2) --j1;

		if (i<=j)
		{
			int first=gropi2[i].second, last=gropi2[j].second;
			ans+=j-i+1;
			if (gropi[i1].second!=first)
			{
				first=3-first;
				++ans;
			}
			if (gropi[j1].second!=last)
			{
				last=3-last;
				++ans;
			}
			if (first!=x1) --ans;
			if (last==x2) ++ans;
		}
		else
		{
			int aux=upper_bound(gropi.begin(),gropi.begin()+n,make_pair(y1,x1))-gropi.begin();
			while(aux<n && gropi[aux].first<=y1) ++aux;
			if (aux<n && gropi[aux].first<y2)
			{
				if (gropi[aux].second==x1) ++ans;
				if (gropi[aux].second==x2) ++ans;
			}
			else
				if (x1!=x2) ++ans;
		}

		fprintf(fout,"%d\n",ans);
	}
	fclose(fin);
	fclose(fout);

	return 0;
}