Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- const int N = 1e4 + 7, M = 1e5 + 7;
- vector<pair<int, int>> graph[N];
- int dsu[N], sz[N], n, m, s, t, answer = INT_MAX;
- set<int> act;
- tuple<int, int, int> arr[M];
- vector<int> comp[N];
- int get(int v) {
- if (dsu[v] == v) {
- return v;
- }
- return dsu[v] = get(dsu[v]);
- }
- void merge(int a, int b) {
- a = get(a);
- b = get(b);
- if (a == b) {
- return;
- }
- if (sz[a] < sz[b]) {
- swap(a, b);
- }
- sz[a] += sz[b];
- dsu[b] = a;
- for (auto i : comp[b]) {
- comp[a].push_back(i);
- }
- }
- int main() {
- ios::sync_with_stdio(0);
- cin.tie(0); cout.tie(0);
- cin >> n >> m;
- for (int i = 0; i < m; ++i) {
- int a, b, c;
- cin >> a >> b >> c;
- a--; b--;
- graph[a].emplace_back(b, c);
- graph[b].emplace_back(a, c);
- arr[i] = { c, a , b };
- }
- cin >> s >> t;
- s--; t--;
- sort(arr, arr + m);
- iota(dsu, dsu + n, 0);
- fill(sz, sz + n, 1);
- for (int i = 0; i < n; ++i) {
- comp[i].push_back(i);
- }
- for (auto i : graph[s]) {
- if (get(i.first) == get(t)) {
- act.insert(i.second);
- answer = min(answer, i.second);
- }
- }
- for (int i = 0; i < m; ++i) {
- int a, b, c;
- tie(c, a, b) = arr[i];
- if (get(s) == get(t) || (!act.empty() && c > *act.begin())) {
- break;
- }
- if (get(a) == get(b)) {
- continue;
- }
- if (get(a) != get(s)) {
- swap(a, b);
- }
- if (get(a) == get(s) && get(b) == get(t)) {
- answer = min(answer, c + *act.begin());
- break;
- }
- if (get(a) == get(s)) {
- for (auto i : comp[get(b)]) {
- for (auto j : graph[i]) {
- if (get(j.first) == get(t)) {
- act.insert(j.second);
- }
- }
- }
- merge(a, b);
- if (!act.empty()) {
- answer = min(answer, c + *act.begin());
- }
- continue;
- }
- if (get(a) != get(t)) {
- swap(a, b);
- }
- if (get(a) == get(t)) {
- for (auto i : comp[get(b)]) {
- for (auto j : graph[i]) {
- if (get(j.first) == get(s)) {
- act.insert(j.second);
- }
- }
- }
- merge(a, b);
- if (!act.empty()) {
- answer = min(answer, c + *act.begin());
- }
- continue;
- }
- merge(a, b);
- }
- cout << answer << "\n";
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement