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

版权声明: https://blog.csdn.net/leelitian3/article/details/82717983

大的思路:无权图的最短路径问题,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;
}

猜你喜欢

转载自blog.csdn.net/leelitian3/article/details/82717983