本题链接:201409-4 最优配餐
本博客给出本题截图:
C++
#include <iostream>
#include <queue>
#include <cstring>
#include <map>
#define x first
#define y second
using namespace std;
const int N = 1010;
typedef long long LL;
typedef pair<int, int> PII;
int n, m, k, d;
queue<PII> q;
int dist[N][N];
bool g[N][N];
struct Custom
{
int a, b, c;
}cus[N * N];
void bfs()
{
int dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1};
while (q.size())
{
auto t = q.front();
q.pop();
for (int i = 0; i < 4; i ++ )
{
int a = t.x + dx[i], b = t.y + dy[i];
if (a < 1 || a > n || b < 1 || b > n || g[a][b]) continue;
if (dist[a][b] > dist[t.x][t.y] + 1)
{
dist[a][b] = dist[t.x][t.y] + 1;
q.push({a, b});
}
}
}
}
int main()
{
scanf("%d%d%d%d", &n ,&m, &k, &d);
memset(dist, 0x3f, sizeof dist);
while (m -- )
{
int x, y;
scanf("%d%d", &x, &y);
dist[x][y] = 0;
q.push({x, y});
}
for (int i = 0; i < k; i ++ )
scanf("%d%d%d", &cus[i].a, &cus[i].b, &cus[i].c);
for (int i = 0; i < d; i ++ )
{
int x, y;
scanf("%d%d", &x, &y);
g[x][y] = true;
}
bfs();
LL res = 0;
for (int i = 0; i < k; i ++ )
res += dist[cus[i].a][cus[i].b] * cus[i].c;
printf("%lld\n", res);
return 0;
}
总结
多源BFS 板子题