求调,WA on #9,悬关
查看原帖
求调,WA on #9,悬关
495495
ljlawa楼主2023/2/11 18:43
#include <bits/stdc++.h>

#define pii pair<int, int>

using namespace std;

const int N = 3005;
const int M = N * N;
const int dx[] = {0, -1, 1, 0};
const int dy[] = {-1, 0, 0, 1};

struct node
{
	int x, y, z;
} a1, a2;

int n, m, k;
int a[N][N];
int sum[N][N];
bool vis[N][N];
int sum1[N][N];
bool vis1[N][N];
int x[M], y[M];
int c[M], d[M];
int ans;
queue <pii> q;
queue <pii> q1;

int main()
{
	a1.z = a2.z = 99999999;
	
	scanf ("%d%d%d", &n, &m, &k); 
	
	for (int i = 1; i <= n; i ++)
		for (int j = 1; j <= m; j ++)
			scanf ("%d", &a[i][j]);
	
	q.push (make_pair(1, 1));
	while (q.size())
	{
		pii x = q.front();
		q.pop();
		if (vis[x.first][x.second] == 1) continue;
		vis[x.first][x.second] = 1;
		for (int i = 0; i < 4; i ++)
		{
			int xx = dx[i];
			int yy = dy[i];
			if (a[x.first + xx][x.second + yy] == 0) sum[x.first + xx][x.second + yy] = 99999999;
			else if (vis[x.first + xx][x.second + yy] == 0 && x.first + xx > 0 && x.first + xx <= n && x.second + yy > 0 && x.second + yy <= m)
			{
				sum[x.first + xx][x.second + yy] = sum[x.first][x.second] + 1;
				q.push (make_pair(x.first + xx, x.second + yy));
			}
		}
	}

	for (int i = 1; i <= n; i ++)
	{
		for (int j = 1; j <= m; j ++)
		{
			if (sum[i][j] == 0 && (i != 1 || j != 1)) sum[i][j] = 99999999;
		}
	}
	
	q1.push (make_pair(n, m));
	while (q1.size())
	{
		pii x = q1.front();
		q1.pop();
		if (vis1[x.first][x.second] == 1) continue;
		vis1[x.first][x.second] = 1;
		for (int i = 0; i < 4; i ++)
		{
			int xx = dx[i];
			int yy = dy[i];
			if (a[x.first + xx][x.second + yy] == 0) sum1[x.first + xx][x.second + yy] = 99999999;
			else if (vis1[x.first + xx][x.second + yy] == 0 && x.first + xx > 0 && x.first + xx <= n && x.second + yy > 0 && x.second + yy <= m)
			{
				sum1[x.first + xx][x.second + yy] = sum1[x.first][x.second] + 1;
				q1.push (make_pair(x.first + xx, x.second + yy));
			}
		}
	}
	
	for (int i = 1; i <= n; i ++)
	{
		for (int j = 1; j <= m; j ++)
		{
			if (sum1[i][j] == 0 && (i != n || j != m)) sum1[i][j] = 99999999;
		}
	}
	
	for (int i = 1; i <= k; i ++)
	{
		int z1, z2;
		scanf ("%d%d", &x[i], &y[i]);
		if (a[x[i]][y[i]] == 0) continue;
		z1 = sum[x[i]][y[i]];
		z2 = sum1[x[i]][y[i]];
		c[i] = z2;
		d[i] = a[x[i]][y[i]];
		if (z1 < a1.z)
		{
			a1.x = x[i];
			a1.y = y[i];
			a1.z = z1;
		}
	}
	
	for (int i = 1; i <= k; i ++)
	{
		if (c[i] == a2.z)
		{
			if (a[a1.x][a1.y] == d[i])
			{
				a2.x = x[i];
				a2.y = y[i];
				a2.z = c[i];
			}
		}
		if (c[i] < a2.z)
		{
			a2.x = x[i];
			a2.y = y[i];
			a2.z = c[i];
		}
	}

	if (a[a1.x][a1.y] == a[a2.x][a2.y]) ans = (a1.z + a2.z + 1);
	else ans = (a1.z + a2.z + 2);
	if (sum[n][m] == 0 && (n != 1 || m != 1)) sum[n][m] = 99999999;
	ans = min (ans, sum[n][m]);
	if (ans >= 99999999) ans = -1;
	printf ("%d", ans);
	
    return 0;
}

2023/2/11 18:43
加载中...