Cod sursa(job #431516)

Utilizator iuly2freemanVasiliev Iulian iuly2freeman Data 1 aprilie 2010 08:56:51
Problema Matrice 2 Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.65 kb
#include <iostream>
#include <fstream>

using namespace std;

ifstream fin("matrice2.in");
ofstream fout("matrice2.out");

int n, q, a[301][301], qu[20000][4], s[20000];
int maxi;
bool pos[300][300];

inline void citire()
{
	fin >> n >> q;
	
	for (int i = 1; i <= n; ++i)
	{
		for (int j = 1; j <= n; ++j)
		{
			fin >> a[i][j];
			if (a[i][j] > maxi) maxi = a[i][j];
		}
	}
	
	for (int i = 0; i < q; ++i)
	{
		fin >> qu[i][0] >> qu[i][1] >> qu[i][2] >> qu[i][3];
	}
}

inline void rem_val(int val)
{
	for (int i = 1; i <= n; ++i)
	{
		for (int j = 1; j <= n; ++j)
		{
			if (a[i][j] == val) a[i][j] = 0;
		}
	}
}

inline void clear()
{
    for (int i = 1; i <= n; ++i)
    {
        for (int j = 1; j <= n; ++j)
		{
			if (!a[i][j]) pos[i][j] = true;
			else pos[i][j] = false;
		}
    }
    
    for (int i = 0; i <= n + 1; ++i)
    {
        pos[0][i] = pos[n + 1][i] = pos[i][0] = pos[i][n + 1] = true;   
    }
}

inline bool fill(int x1, int y1, int x2, int y2)
{
    if (pos[x1][y1]) return false;
	
    pos[x1][y1] = true;
	
    if (pos[x2][y2]) return true;
	
	bool shit = false;
	
	shit |= fill(x1 + 1, y1,     x2, y2);
	if (!shit) shit |= fill(x1 - 1, y1,     x2, y2);
	if (!shit) shit |= fill(x1,     y1 + 1, x2, y2);
	if (!shit) shit |= fill(x1,     y1 - 1, x2, y2);
	    
    return shit;
}

int main()
{
	citire();
	
	for (int i = 1; i <= maxi; ++i)
	{
		for (int j = 0; j < q; ++j)
		{
			if (!s[j])
			{
				if (a[qu[j][0]][qu[j][1]] == i || a[qu[j][2]][qu[j][3]] == i) s[j] = i;
				clear();
				if (!fill(qu[j][0], qu[j][1], qu[j][2], qu[j][0])) s[j] = i - 1;                
			}
		}
				
		rem_val(i);
	}
	
	for (int i = 0; i < q; ++i) fout << s[i] << "\n";
	
	return 0;
}