Cod sursa(job #1227400)

Utilizator space.foldingAdrian Soucup space.folding Data 10 septembrie 2014 12:46:29
Problema Car Scor 10
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.46 kb
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <string>
#include <map>
#include <set>
#include <cmath>
#include <fstream>
#include <ctime>
#include <bitset>
#include <limits>
#include <numeric>
#include <list>
#include <cstdlib>
#include <iomanip>
#include <vector>
#include <queue>
#include <stack>
#include <cctype>
using namespace std;
#define x first
#define y second



bool a[501][501];
bool b[501][501];
int cst[501][501];
int pvd[501][501];

int dx[] = {-1, 0, 1, 1, 1, 0, -1, -1};
int dy[] = {-1, -1, -1, 0, 1, 1, 1, 0};

int n, m;


int getCost(int k, int ndir) {
	if(k == ndir) 
		return 0;

	int lenk = dx[k] * dx[k] + dy[k] * dy[k];
	int lenndir = dx[ndir] * dx[ndir] + dy[ndir] * dy[ndir];

	int dot = dx[k] * dx[ndir] + dy[k] * dy[ndir];

	if(dot == 0)
		return 2;

	if(dot < 0 && lenk * lenndir == 2) return 3;
	if(dot > 0 && lenk * lenndir == 2) return 1;

	if(dot > 0) return 0;
	else return 4;
}

struct kpair {
	int first;
	int second;
	int cost;
};

struct kpairless {
	bool operator() (kpair const &left, kpair const &right) {
		return left.cost < right.cost;
	}
};

int minCost(int sx, int sy, int ex, int ey, int k) {


	
	for(int i = 0; i < n; i++)
		for(int j = 0; j < m; j++)
			cst[i][j] = 4000000;

	cst[sy][sx] = 0;
	pvd[sy][sx] = k;
	int prevDir = k;

	priority_queue<kpair, vector< kpair>, kpairless> q;

	q.push({sx, sy, 0});

	while(!q.empty()) {
		int minIdx = 0;

		kpair el = q.top();
		q.pop();

		a[el.y][el.x] = 1;
		prevDir = pvd[el.y][el.x];
		
		for(int i = 0; i < 8; i++) {

			int nx = dx[i] + el.x;
			int ny = dy[i] + el.y;

			if(nx >= 0 && nx < m && ny >=0 && ny < n && !a[ny][nx]) {
				if(cst[ny][nx] > getCost(prevDir, i) + cst[el.y][el.x]) {
					cst[ny][nx] = getCost(prevDir, i) + cst[el.y][el.x];
					pvd[ny][nx] = i;
					q.push({nx, ny, cst[ny][nx]});
				}
			}
		}
	}
	return cst[ey][ex];
}

int main () {
	freopen("car.in", "r", stdin);
	freopen("car.out", "w", stdout);

	cin >> n >> m;

	int ex, ey, sx, sy;

	cin >> sy >> sx >> ey >> ex;



	for(int i = 0; i < n; i++)
		for(int j = 0; j < m; j++)
			cin >> b[i][j];

	int minc = 4000000;
	for(int k = 0; k < 8; k++) {

		for(int i = 0; i < n; i++)
			for(int j = 0; j < m; j++)
				a[i][j] = b[i][j];

		minc = min(minCost(sx - 1, sy - 1, ex - 1, ey - 1, k), minc);
	}

	cout << (minc == 4000000 ? -1 : minc);

	return 0;
}