当前位置: 代码迷 >> 综合 >> POJ 2607 Fire Station
  详细解决方案

POJ 2607 Fire Station

热度:16   发布时间:2024-01-13 18:19:31.0

又是一道最短路的题,为了提高效率,我用的邻接链表+SPFA做的,速度很快,0ms过的。

首先,初始化完dist数组后,对每个消防站作为起点都求一次最短路,期间不再初始化dist数组,这样最后得到的dist数组就是每个居民到最近的消防站的距离。

然后枚举每个点,每次求一下最短路,用其中的最大值比较一下。 然后这个代码贴到zoj上是过不了的,因为那里的输入很恶心人。还有空行神马的。

/*
ID: sdj22251
PROG: subset
LANG: C++
*/
#include <iostream>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <map>
#include <string>
#include <cstring>
#include <cmath>
#include <ctime>
#define LOCA
#define MAXN 505
#define INF 0x0fffffff
#define eps 1e-7
using namespace std;
struct node
{int v, w;node *next;
} edge[MAXN];
int d[MAXN], dd[MAXN], n, m, fire[MAXN];
int q[MAXN * 3];
bool visited[MAXN];
void spfa(int src, int *ecost)
{int h, t, u, i;node *ptr;h = 0, t = 1;memset(visited, 0, sizeof(visited));q[0] = src;ecost[src] = 0;visited[src] = true;while(h < t){u = q[h++];visited[u] = false;ptr = edge[u].next;while(ptr){if(ecost[ptr -> v] > ecost[u] + ptr -> w){ecost[ptr -> v] = ecost[u] + ptr -> w;if(!visited[ptr -> v]){q[t++] = ptr -> v;visited[ptr -> v] = true;}}ptr = ptr -> next;}}
}
void insert(const int &x, const int &y, const int &w)
{node *ptr = new node;ptr -> v = y;ptr -> w = w;ptr -> next = edge[x].next;edge[x].next = ptr;
}
int main()
{
#ifdef LOCALfreopen("d:/data.in","r",stdin);freopen("d:/data.out","w",stdout);
#endifchar s[140];int i, u, v, w, j;while(scanf("%d%d", &m, &n) != EOF){for(i = 0; i < m; i++){scanf("%d", &fire[i]);}int mi = INF;int ans = 1;for(i = 0; i <= n; i++){edge[i].next = NULL;}while(scanf("%d%d%d", &u, &v, &w) != EOF){insert(u, v, w);insert(v, u, w);}for(i = 0; i <= n; i++)d[i] = INF;for(i = 0; i < m; i++)spfa(fire[i], d);for(i = 1; i <= n; i++){int mx = 0;if(d[i] == 0) continue;for(j = 0; j <= n; j++)dd[j] = d[j];spfa(i, dd);for(j = 1; j <= n; j++)mx = max(mx, dd[j]);if(mi > mx){mi = mx;ans = i;}}printf("%d\n", ans);}return 0;
}


  相关解决方案