POJ 2607 SPFA

求出所有FireStation到其它的Intersection的距离,再求出基它Intersection到其它点的距离,然后比较距离就OK了

用SPFA +AdjacencyList 的速度较快 用Dijkstra会超时


题目测试数据:http://plg1.cs.uwaterloo.ca/~acm00/990925.data/






#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
#define MAXN 510
struct node
{
	int v;
	int w;
	node* next;
};
inline void AdjacencyList(int u,int v,int w,node edge[])
{
	node* NewNode = new node;
	NewNode -> v = v;
	NewNode -> w = w;
	NewNode -> next = edge[u].next;
	edge[u].next = NewNode;
}
int qu[MAXN * 4];
void spfa(int start,int d[],node edge[])
{
	bool visit[MAXN];
	memset(visit,false,sizeof(visit));
	qu[0] = start;
	d[start] = 0;
	visit[start] = true;
	int head = 0;
	int tail = 1;
	while(head < tail)//queue.empty
	{
	/*	cout<<"qu"<<endl;
		for(int i = head; i < tail; i++)
		{
			cout<<qu[i]<<" ";
		}*/
	//	cout<<endl;
		int u = qu[head++];
		visit[u] = false;//不在队列
		node* ptr = edge[u].next;
		while(ptr)
		{
			if(d[ptr -> v] >  d[u] + ptr -> w)
			{
				d[ptr -> v] = d[u] + ptr -> w;
				if(visit[ptr -> v] == false)
				{
					qu[tail++] = ptr -> v;//成功松驰加入队列
					visit[ptr -> v] = true;//在队列里面
				}
			}
			ptr = ptr -> next;
		}
	}
	/*cout<<"d"<<endl;
	for(int i = 1; i <= SumInter; i++)
	{
		cout<<d[i]<<" ";
	}
	cout<<endl;*/
}
int main()
{
	int SumFire,SumInter;
	int fire[MAXN];
	//freopen("A.3.dat","r",stdin);
	while(scanf("%d %d",&SumFire,&SumInter) != EOF)
	{
		
		int i;
		int d[MAXN];
		memset(d,127,sizeof(d));
		node edge[MAXN];
		for(i = 0; i <= SumInter; i++)
		{
			edge[i].next = NULL;
		}
		for(i = 0; i < SumFire; i++)
		{
			scanf("%d",&fire[i]);
		}
		int from,to,w;
		while(scanf("%d %d %d",&from,&to,&w) != EOF)
		{
			AdjacencyList(from,to,w,edge);
			AdjacencyList(to,from,w,edge);
		}
		for(i = 0; i < SumFire; i++)
		{
			spfa(fire[i],d,edge);
		}
		int dis[MAXN];
		int ans;
		memset(&ans,127,sizeof(ans));
		int flag;
		flag = 1;
		for(i = 1; i <= SumInter; i++)
		{
			if(d[i] == 0)
			{
				continue;
			}
			memcpy(dis,d,sizeof(dis));
			spfa(i,dis,edge);
			int MaxEdge = 0;
			int j;
			for(j = 1; j <= SumInter; j++)
			{
				if(dis[j] > MaxEdge)
				{
					MaxEdge = dis[j];
				//cout<<"MaxEdge"<<MaxEdge<<endl;
				}
			}
			if(MaxEdge < ans)
			{
				ans = MaxEdge;
				flag = i;
			}
		}
		printf("%d\n",flag);
		
	}
	return 0;
}


你可能感兴趣的:(struct,测试,null)