例题6-20(uva-1599)

#include <iostream>
#include <istream>
#include <sstream>
#include <vector>
#include <stack>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <cstring>
#include <unordered_map>
#include <unordered_set>
#include <algorithm>
#include <numeric>
#include <chrono>
#include <ctime>
#include <cmath>
#include <cctype>
#include <string>
#include <cstdio>
#include <iomanip>


#include <thread>
#include <mutex>
#include <condition_variable>
#include <functional>
#include <iterator>
using namespace std;
const int MLEN = 1e5 + 7, INF = 1e9 + 7;

struct Node {
	int to, next, color;
	Node(int t = 0, int n = 0, int c = 0) :to(t), next(n), color(c) {}
}tail[MLEN << 2];

int head[MLEN] = { 0 }, d[MLEN] = { 0 }, vis[MLEN] = { 0 }, cnt = 0, n, m;
vector<int> ans;

void AddEdge(int from, int to, int color) {
	tail[++cnt].to = to;
	tail[cnt].color = color;
	tail[cnt].next = head[from];
	head[from] = cnt;
}

void Distance() {
	d[n] = 0;
	queue<int> q;
	q.push(n);
	while (!q.empty()) {
		int u = q.front(); q.pop();
		for (int i = head[u]; i; i = tail[i].next) {
			int id = tail[i].to;
			if (d[id] != -1) continue;
			d[id] = d[u] + 1;
			q.push(id);
		}
	}
}
void Bfs() {

	cout << d[1] << endl;
	
	int first = 1;
	vector<int> arr = { 1 }, temp;

	int cc = d[1];
	while (cc--) {
		temp.clear();
		int len = arr.size(), c = INF,ne = 0;
		for (int i = 0; i < len; ++i) {
			int u = arr[i];
			for (int j = head[u]; j; j = tail[j].next) {
				int id = tail[j].to;
				if (vis[id] || d[u] - d[id] != 1) { continue; }

				if (c > tail[j].color) {
					ne = id;
					c = tail[j].color;
				}
			}
		}

		for (int i = 0; i < len; ++i) {
			int u = arr[i];
			for (int j = head[u]; j; j = tail[j].next) {
				int id = tail[j].to;
				if (vis[id] || d[u] - d[id] != 1) { continue; }
				if (tail[j].color == c) {
					vis[id] = 1;
					temp.emplace_back(id);
				}
			}
		}

		if (!first) cout << " ";
		else first = 0;

		cout << c;
		arr = temp;
	}
	cout << endl;
}

int main()
{
	int a, b, c;
	while (cin >> n >> m) {
		cnt = 0;
		for (int i = 0; i <= n; ++i) {
			d[i] = -1;
			vis[i] = head[i] = 0;
		}

		for (int i = 0; i < m; ++i) {
			cin >> a >> b >> c;
			AddEdge(a, b, c);
			AddEdge(b, a, c);
		}
		Distance();
		Bfs();
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值