CCF 201409-4 最优配餐

CCF 201409-4 最优配餐 传送门

这道题很水, 不过刚开始超时了. 有一个收获: 对一张图里分散的点进行BFS时, 不必每次都将其作为源点, 进行BFS. 而可以全部压入队列中, 进行BFS.

#include <algorithm>
#include <iostream>
#include <cstring>
#include <vector>
#include <queue>
using namespace std;

int map[1005][1005], cnt[1005][1005];
int lenth[1005][1005], n; // 路长
long long ans = 0;
bool vis[1005][1005];
int move[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
queue<pair<int,int> > Q;

void bfs()
{
    while (!Q.empty()) {
        register int x = Q.front().first, y = Q.front().second;
        Q.pop();
        for (register int i = 0; i < 4; ++i) {
            register int xx = x + move[i][0], yy = y + move[i][1];
            if (vis[xx][yy]) continue;
            if (map[xx][yy] == -1 || map[xx][yy] == -2) continue;
            if (xx < 1 || xx > n || yy < 1 || yy > n) continue;
            vis[xx][yy] = true;
            if (lenth[xx][yy] < lenth[x][y] + 1) continue;
            lenth[xx][yy] = lenth[x][y] + 1;
            Q.push(make_pair(xx, yy));
        }
    }
}

int main()
{
    ios::sync_with_stdio(false);
    register int m, k, d;
    cin >> n >> m >> k >> d;
    memset(map, 0, sizeof(map));
    memset(cnt, 0, sizeof(cnt));
    memset(lenth, 0x3f, sizeof(lenth));
    memset(vis, false, sizeof(vis));
    for (register int i = 0, x, y; i < m; ++i) {
        cin >> x >> y;
        map[x][y] = -2; // 分店
        lenth[x][y] = 0;
    }
    for (register int i = 0, x, y, c; i < k; ++i) {
        cin >> x >> y >> c;
        map[x][y] = 1;
        cnt[x][y] += c; // 购物数量
    }
    for (register int i = 0, x, y; i < d; ++i) {
        cin >> x >> y;
        map[x][y] = -1;
    }
    for (register int i = 1; i <= n; ++i) {
        for (register int j = 1; j <= n; ++j) {
            if (map[i][j] == -2) {
                Q.push(make_pair(i, j));
                vis[i][j] = true;
            }
        }
    }
    bfs();
    for (register int i = 1; i <= n; ++i) {
        for (register int j = 1; j <= n; ++j) {
            if (map[i][j] == 1) {
                ans += cnt[i][j]*lenth[i][j];
            }
        }
    }
    cout << ans;
}

猜你喜欢

转载自blog.csdn.net/wjh2622075127/article/details/81625933
今日推荐