uva 1599双向bfs 博客分类: 算法题
程序员文章站
2024-03-24 22:05:10
...
//0.140s #include<iostream> #include<queue> #include<cstring> #include<vector> using namespace std; const int maxn = 100005; const int inf = 1 << 30; int i, a, b, c, n, m; bool vis[maxn]; struct node { int v; int c; node* next; }G[maxn * 4]; node *adj[maxn], *cur, *p; int path[maxn], d[maxn], w[maxn], bs; void rev_bfs() { memset(d, 0, (n + 1) * sizeof(int)); d[n] = 1; queue<int> q; q.push(n); while (!q.empty()) { a = q.front(); q.pop(); if (d[1] && d[a] >= d[1]) { continue;//剪枝1 } for (p = adj[a]; p; p = p->next) { b = p->v; if (!d[b]) { d[b] = d[a] + 1; q.push(b); } } } } void bfs() { memset(vis,0, sizeof(vis)); vis[1] = true; vector<int> q1; q1.push_back(1); m = d[1]-1; while(m){ bs = inf; for (i = 0; i < q1.size(); i++) { a = q1[i]; for (p = adj[a]; p; p = p->next) { b = p->v; c = p->c; if (d[b] == m && c < bs) bs = c; } } vector<int> q2; for (i = 0; i < q1.size(); i++) { a = q1[i]; for (p = adj[a]; p; p = p->next) { b = p->v; if (p->c == bs && d[b] == m && !vis[b]) { vis[b] = true;//剪枝2 q2.push_back(b); //cout<<a<<'-'<<bs<<'-' << p->v << endl; } } } w[m--] = bs; q1 = q2; } printf("%d\n", d[1]-1); printf("%d", w[d[1]-1]); for (i =d[1]-2; i >0; i--) { printf(" %d", w[i]); } printf("\n"); } int main() { while (scanf("%d%d", &n, &m) == 2) { memset(adj, 0, sizeof(adj)); cur = G; for (i = 0; i < m; i++) { scanf("%d%d%d", &a, &b, &c); cur->v = b; cur->c = c; cur->next = adj[a];//从前面插入 adj[a] = cur++; cur->v = a; cur->c = c; cur->next = adj[b]; adj[b] = cur++; } rev_bfs(); bfs(); } return 0; } /* 4 6 1 2 1 1 3 2 3 4 3 2 3 1 2 4 4 3 1 1 */
上一篇: solr4.0安装和使用
下一篇: Android MTU 值修改