昨天的 arc177_c,从标程里第一次知道 tuple 这个东西,但是发生了一个奇怪的事
我如果写成这样
q.push(make_tuple(sx, sy, 0));
q.push(make_tuple(tx, ty, dist[tx][ty]));
并这样调用
int x = get<0>(q.top()), y = get<1>(q.top());
输出来的 dist 矩阵就是这样
5
RBRBB
RBRRR
RRRBR
RBBRB
BBRBR
0 1 1 2 2
0 1 0 1 1
0 0 0 1 1
0 1 1 1 2
1 2 1 2 2
2 1 1 0 0
2 1 2 1 1
3 2 2 1 2
3 2 2 2 2
2 2 3 2 3
4
第一个图就发生错误计算,为什么?
且改成形如 {dist[x][y], x, y},把 dist 放前边,坐标调用 get<1> 和 get<2> 就又正常了?
附:
#include <bits/stdc++.h>
#define re register int
using namespace std;
typedef tuple<int, int, int> tp;
const int N = 510, inf = 0x3f3f3f3f;
const int dx[4] = {-1, 0, 1, 0};
const int dy[4] = {0, 1, 0, -1};
char g[N][N];
int n, res1, res2, dist[N][N];
bool vis[N][N];
priority_queue< tp, vector<tp>, greater<tp> > q;
inline int work(int sx, int sy, int ex, int ey, char c)
{
memset(vis, false, sizeof(vis));
for (re i = 1; i <= n; i ++)
for (re j = 1; j <= n; j ++) dist[i][j] = inf;
dist[sx][sy] = 0;
q.push(make_tuple(sx, sy, 0));
while (!q.empty())
{
int x = get<0>(q.top()), y = get<1>(q.top());
q.pop();
if (vis[x][y]) continue;
vis[x][y] = true;
for (re i = 0; i < 4; i ++)
{
int tx = x + dx[i], ty = y + dy[i];
if (tx < 1 || tx > n || ty < 1 || ty > n) continue;
int w = (g[tx][ty] == c ? 0 : 1);
if (dist[x][y] + w < dist[tx][ty])
{
dist[tx][ty] = dist[x][y] + w;
q.push(make_tuple(tx, ty, dist[tx][ty]));
}
}
}
/*
for (re i = 1; i <= n; i ++)
{
for (re j = 1; j <= n; j ++) cout << dist[i][j] << ' ';
cout << '\n';
}
*/
return dist[ex][ey];
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
cin >> n;
for (re i = 1; i <= n; i ++)
for (re j = 1; j <= n; j ++) cin >> g[i][j];
res1 = work(1, 1, n, n, 'R');
res2 = work(1, n, n, 1, 'B');
cout << res1 + res2 << '\n';
return 0;
}