【CCF 201409-4】最优配餐(BFS)

大的思路:无权图的最短路径问题,BFS解决

思路1:对所有分店为源点,进行BFS,找到每为顾客的最短距离。【超时】

尝试减枝:每次BFS若遇到距离比原来的大,即停止搜索。【依旧超时】

思路2:将所有的分店都加入队列,进行一次BFS【100分】

#include <iostream>
#include <iomanip>
#include <cmath>
#include <cstring>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <algorithm>
#include <sstream>
#include <list>
#define nmax 1005
using namespace std;

struct Node
{
	int x, y;
	Node(int a, int b):x(a), y(b) {}
};

const int inf = 1e8;
int n,m,k,d,x,y;
int shop_x[nmax*nmax];
int shop_y[nmax*nmax];
int cos_x[nmax*nmax];
int cos_y[nmax*nmax];
int cos_n[nmax*nmax];

bool vis[nmax][nmax];
int dis[nmax][nmax];
queue<Node> que;
int dir[4][2] = {{1,0},{-1,0},{0,1},{0,-1}};

inline bool is_legal(int x, int y)
{
	if(x <= 0 || x > n || y <= 0 || y > n) return 0;
	if(vis[x][y] || dis[x][y] == inf) return 0;
	return 1;
}

void bfs()
{
	int x,y,r,c;
	memset(vis, 0, sizeof(vis));
	for(int i=0; i<m; ++i)
	{
		que.push(Node(shop_x[i], shop_y[i]));
		dis[shop_x[i]][shop_y[i]] = 0;
		vis[shop_x[i]][shop_y[i]] = 1;
	}

	while(!que.empty())
	{
		x = que.front().x;
		y = que.front().y;
		vis[x][y] = 1;
		//cout<<"("<<x<<","<<y<<"): "<<dis[x][y]<<"\n";
		que.pop();

		for(int i=0; i<4; ++i)
		{
			r = x + dir[i][0];
			c = y + dir[i][1];

			if(is_legal(r, c))
			{
				dis[r][c] = dis[x][y] + 1;
				vis[r][c] = 1;
				que.push(Node(r,c));
			}
		}
	}
}

int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);

	memset(dis,0x3f3f3f3f,sizeof(dis));
	cin>>n>>m>>k>>d;
	for(int i=0; i<m; ++i)
		cin>>shop_x[i]>>shop_y[i];
	for(int i=0; i<k; ++i)
		cin>>cos_x[i]>>cos_y[i]>>cos_n[i];
	for(int i=0; i<d; ++i)
	{
		cin>>x>>y;
		dis[x][y] = inf;
	}

	bfs();

	unsigned long long sum = 0;
	for(int i=0; i<k; ++i)
		sum += dis[cos_x[i]][cos_y[i]] * cos_n[i];
	cout<<sum;
	return 0;
}

 

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值