anLA_的专栏

记录知识的地方~记录成长的地方~

1003. Emergency (25)

pat

这题大概意思是,众多城市点,然后某一个城市发生火灾,求你所在城市到目标城市的最短路径,并且能够赶到目标城市的最多消防员,

也就是最短路径上涉及所有的消防员之和。

解题心得:

  1、Dijkstra算法,就是求源点到目标点最短路径。这个算法有点忘,看了书,后来才回想起来。

2、dijkstra算法的意思,就是把点分为两个集合,一个集合是已经算出最短路径,另一个就是待算的,

每次从已经求到的最短路径集合里面找出最短,再去和未知集合比较,从而更改源点到目标点的距离,

将求得的点标记好,放入到已经求成功的集合。

3、map[myStart][myEnd] = map[myEnd][myStart] = myLength;  就是这一句,一开始理解为有向图,

以为只有一个方向的,然后没有把后者加上。

代码如下:

#include"stdio.h"
#include"string.h"
#include"math.h"
#include<iostream>
#include<vector>
using namespace std;
#define INF 0x7FFFFFFF
struct city{
	int roadNum;
	int emergencyNum;
	int distance;
};
vector<int> team;
vector<bool> visit;
vector<vector<int>> map;
vector<struct city> cities;

int countShortest(){
	int min = INF;
	int index = -1;
	for(int i = 0;i < cities.size();i++){
		if(visit[i] == false && cities[i].distance < min){
			min = cities[i].distance;
			index = i;
		}
	}
	return index;
}

void digistra(int start,int end){
	//initialization
	for(int i = 0;i < cities.size();i++){
		cities[i].distance = INF;
		cities[i].emergencyNum = 0;
		cities[i].roadNum = 0;
	}
	cities[start].distance = 0;
	cities[start].emergencyNum = team[start];
	cities[start].roadNum = 1;

	//monify the shortest ways of each point
	while(true){
		int index = countShortest();
		if(index == -1){
			return;
		}
		visit[index] = true;
		if( index == end ){
			return;
		}
		for(int i = 0;i < cities.size();i++){
			if(visit[i] || map[index][i] == INF){
				continue;
			}
			//modify
			if(cities[i].distance > cities[index].distance + map[index][i]){
				cities[i].distance =  cities[index].distance + map[index][i];
				cities[i].emergencyNum = cities[index].emergencyNum + team[i];
				cities[i].roadNum = cities[index].roadNum;
			}else if(cities[i].distance == cities[index].distance + map[index][i]){
				cities[i].roadNum += cities[index].roadNum;
				if(cities[i].emergencyNum < cities[index].emergencyNum + team[i]){
					cities[i].emergencyNum = cities[index].emergencyNum + team[i];
				}
			}
		}

	}
}

int main(){
	int cityNum;
	while(scanf("%d",&cityNum) != EOF){
		int roadNum,startPoint,endPoint;
		scanf("%d%d%d",&roadNum,&startPoint,&endPoint);
		team.resize(cityNum);

		visit.resize(cityNum);
		visit.assign(cityNum,false);
		
		map.resize(cityNum);

		for(int i = 0;i < cityNum;i++)
		map[i].assign(cityNum,INF);
		
		cities.resize(cityNum);

		for(int i = 0;i < cityNum;i++){
			scanf("%d",&team[i]);
		}

		for(int i = 0;i < roadNum;i++){
			int myStart,myEnd,myLength;
			scanf("%d%d%d",&myStart,&myEnd,&myLength);
			if(map[myStart][myEnd] > myLength){     //get the shortest
				map[myStart][myEnd] = map[myEnd][myStart] = myLength;
			}
		}
		digistra(startPoint,endPoint);
		printf("%d %d",cities[endPoint].roadNum,cities[endPoint].emergencyNum);
	}
	return 0;
}


阅读更多
版权声明:本博客所有的原创文章,转载请注明出处,作者皆保留版权。 https://blog.csdn.net/anLA_/article/details/53997586
文章标签: acm c语言 pat
个人分类: pat a
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭