ccf 201409-4 最优配餐 (90分待更新) bfs

点击打开链接

90分代码:

//bfs
#include <iostream>
#include<cstdio>
#include<queue>
#include<cstring>
#include<map>
using namespace std;
typedef long long LL;
typedef pair<int,int>PII;
const int maxn=1000+10;
bool done[maxn][maxn];
int dx[]={0,0,-1,1};
int dy[]={1,-1,0,0};
struct node{
int x,y,dist;
node(int x,int y,int dist):x(x),y(y),dist(dist) {}
};
int n,m,k,d;            //方格大小 起始点数量 终点数量 不能经过的点数量
map<PII,LL>str;
LL bfs()
{
    LL sum=0;
    int cnt=0;              //已经经过的终点数量,作为结束标志
    memset(done,false,sizeof(done));
    queue<node>pq;
    while(!pq.empty()) pq.pop();
    for(int i=0;i<m;i++)
    {
        int x,y;
        scanf("%d%d",&x,&y);
        pq.push(node(x,y,0));
        done[x][y]=true;
    }
    str.clear();
    for(int i=0;i<k;i++)
    {
        int x,y,weight;
        scanf("%d%d%d",&x,&y,&weight);
        str[PII(x,y)]+=weight;
    }
    for(int i=0;i<d;i++)
    {
        int x,y;
        scanf("%d%d",&x,&y);
        done[x][y]=true;
    }
    while(!pq.empty())
    {
        node f=pq.front();
        pq.pop();
        if(str.find(PII(f.x,f.y))!=str.end()) {
            cnt++;
            sum+=(LL)f.dist*str[PII(f.x,f.y)];
        }
        if(cnt==k) return sum;
        for(int i=0;i<4;i++)
        {
            int nx=f.x+dx[i],ny=f.y+dy[i];
            if(nx>=1&&nx<=n&&ny>=1&&ny<=n&&!done[nx][ny])
            {
                    pq.push(node(nx,ny,f.dist+1));
                    done[nx][ny]=true;
            }
        }
    }
}
int main()
{
    scanf("%d%d%d%d",&n,&m,&k,&d);
    cout<<bfs()<<endl;
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值