CCF 201409-4 best catering

Optimal catering

Topic Link
Here Insert Picture Description
Here Insert Picture Description

answer

Bfs multi-source shortest seek grid
that Italy explain a little, in the figure above, under defined without red dot, green dot to find the nearest point of the blue, then the distance weighted sum, for the final answer. For multi-source shortest path problem, the general solution is to create a super source, the question into a single source shortest path problem, and then set a spfa or Dijkstra algorithm can be. However, for the shortest grid problem, only need to consider the use of bfs can be solved, because the right side of the grid is 1, layer by layer search is certainly the shortest, in order not to repeat the search, you need to mark it, the complexity of the final the trellis diagram is equivalent to search again, the O (n ^ 2) 1e6 no problems.

Code

#include <bits/stdc++.h>
using namespace std;
#define IOS ios::sync_with_stdio(false)
#define maxn 1005
#define maxm 800000
#define INF 2000000005
#define ll long long

struct node{
    int x,y,cnt;
};

bool vis[maxn][maxn];
bool ff[maxn][maxn];
int dis[maxn][maxn];
vector<pair<int,int> >st;
vector<node>ed;

int xx[4]={0,1,0,-1};
int yy[4]={1,0,-1,0};
void bfs(int n)
{
    for(int i=0;i<=n;i++)
        for(int j=0;j<=n;j++)
            dis[i][j]=INF;

    queue<pair<int,int> >Q;
    for(int i=0;i<st.size();i++)
    {
        dis[st[i].first][st[i].second]=0;
        vis[st[i].first][st[i].second]=true;
        Q.push(st[i]);
    }

    while(!Q.empty())
    {
        pair<int,int>u=Q.front();
        Q.pop();

        for(int i=0;i<4;i++)
        {
            int nx=xx[i]+u.first;
            int ny=yy[i]+u.second;
            if(nx>0&&nx<=n&&ny>0&&ny<=n&&ff[nx][ny]==false&&vis[nx][ny]==false)
            {
                vis[nx][ny]=true;
                dis[nx][ny]=dis[u.first][u.second]+1;
                Q.push(make_pair(nx,ny));
            }
        }
    }
}

int main()
{
    IOS;
    int n,m,k,d;
    cin>>n>>m>>k>>d;

    for(int i=0;i<m;i++)
    {
        int x,y;
        cin>>x>>y;
        st.push_back(make_pair(x,y));
    }

    for(int i=0;i<k;i++)
    {
        int x,y,z;
        cin>>x>>y>>z;
        ed.push_back(node{x,y,z});
    }

    for(int i=0;i<d;i++)
    {
        int x,y;
        cin>>x>>y;
        ff[x][y]=true;
    }

    bfs(n);

    ll ans=0;
    for(int i=0;i<ed.size();i++)
    {
        ans+=dis[ed[i].x][ed[i].y]*ed[i].cnt;
    }
    cout<<ans;
    return 0;
}

Published 41 original articles · won praise 2 · Views 1223

Guess you like

Origin blog.csdn.net/qq_41418281/article/details/103994584