原题链接:
https://vjudge.net/problem/UVA-1599
分类:图
备注:BFS,逆搜索
思路
按照紫书上的,先在终点开始BFS求出每个点到终点的距离,再从起点开始搜索,每次找邻接结点中能更进一步的点,要比较颜色的字典序来筛选,把最小的都留下。重复此步骤,每次输出最小颜色值即可。
数据挺大的,花了好久时间,终于不是TLE了,不得不说map是真的慢,在速度方面似乎越原始的东西越好,所以直接用结构体来存边的权值。注意不仅仅是在逆向BFS更新距离时要注意用vis[]数组防止点重复入队,在从起点开始搜索时也得判重才能不超时。
代码如下:
#include<cstdio>
#include<vector>
#include<cstring>
#include<queue>
using namespace std;
typedef long long ll;
const ll inf = 1e9 + 5;
const int maxn = 100000 + 5;
int n, m, d[maxn], vis[maxn], nextNode[maxn], tempNode[maxn];
struct edge {
int v, w;
edge(int b, int c) :v(b), w(c) {}
};
vector<edge>e[maxn];
int main(void) {
while (~scanf("%d %d", &n, &m)) {
memset(vis, 0, sizeof(vis));
memset(d, inf, sizeof(d));
for (int i = 1; i <= n; i++)e[i].clear();
while (m--) {
int a, b; ll c;
scanf("%d %d %lld", &a, &b, &c);
e[a].push_back(edge(b, c));
e[b].push_back(edge(a, c));
}
queue<int>Q;
Q.push(n);
vis[n] = 1;
d[n] = 0;
while (!Q.empty()) {
int u = Q.front(); Q.pop();
for (int i = 0; i < e[u].size(); i++) {
int v = e[u][i].v;
if (vis[v])continue;
vis[v] = 1;
d[v] = d[u] + 1;
Q.push(v);
}
}
memset(vis, 0, sizeof(vis));
vis[1] = 1;
int size = 0;
nextNode[size++] = 1;
printf("%d\n", d[1]);
for (int step = 0; step < d[1]; step++) {
int cnt = 0;
ll minColor = inf;
for (int i = 0; i < size; i++) {
int u = nextNode[i];//所有的u和n的距离都相同
for (int j = 0; j < e[u].size(); j++) {
int v = e[u][j].v;
if (d[v] != d[u] - 1)continue;//保证再走一步会缩小距离
if (e[u][j].w <= minColor) {//找最小的颜色
if (e[u][j].w < minColor) {
cnt = 0; minColor = e[u][j].w;
}
tempNode[cnt++] = v;
}
}
}
printf("%lld%c", minColor, (step == d[1] - 1) ? '\n' : ' ');
int cnt2 = 0;
for (int i = 0; i < cnt; i++) {
if (vis[tempNode[i]]) continue;
vis[tempNode[i]] = 1;
nextNode[cnt2++] = tempNode[i];
}
size = cnt2;
}
}
return 0;
}
版权声明:本文为TK_wang_原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。