제출 #392387

#제출 시각아이디문제언어결과실행 시간메모리
3923878e7007 (CEOI14_007)C++14
100 / 100
305 ms17820 KiB
//Challenge: Accepted
#include <iostream>
#include <algorithm>
#include <vector>
#include <utility>
#include <queue>
#define ll long long
#define maxn 200005
#define pii pair<int, int>
#define ff first
#define ss second
#define io ios_base::sync_with_stdio(0);
using namespace std;
//#include <bits/extc++.h>
//using namespace __gnu_pbds;
//template<class T> using Tree = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_upate>;

vector<int> adj[maxn];
int d1[maxn], d2[maxn], d3[maxn], d4[maxn];
bool found[maxn];

void bfs(int n, int s, int dep[]) {
	for (int i = 1;i <= n;i++) found[i] = false;
	queue<int> que;
	que.push(s);
	dep[s] = 0;
	while (que.size()) {
		int cur = que.front();
		que.pop();
		found[cur] = 1;
		for (int v:adj[cur]) {
			if (!found[v]) {
				found[v] = 1;
				dep[v] = dep[cur] + 1;
				que.push(v);
			}
		}
	}
}
int main() {
	io
	int n, m;
	cin >> n >> m;
	int pa, pb, st, st2;
	cin >> pa >> pb >> st >> st2;
	for (int i = 0;i < m;i++) {
		int u, v;
		cin >> u >> v;
		adj[u].push_back(v);
		adj[v].push_back(u);
	}

	bfs(n, st, d1);
	bfs(n, st2, d2);
	bfs(n, pa, d3);
	bfs(n, pb, d4);

	if (d1[pa] == d2[pa] && d1[pb] == d2[pb]) {
		int ans = d1[pb] - d1[pa];
		int ma = 1<<30, mb = 1<<30;
		for (int i = 1;i <= n;i++) {
			if (d3[i] + d1[i] == d1[pa] && d1[i] == d2[i]) { //if on shortest path
				ma = min(ma, d1[i]);
			}
			if (d4[i] + d1[i] == d1[pb] && d1[i] == d2[i]) {
				mb = min(mb, d1[i]);
			}
		}
		if (ma > mb) ans--;
		cout << (ans >= 0 ? ans : -1) << "\n";
	} else {
		int ans = min(d1[pb] - d1[pa], d2[pb] - d2[pa]);
		cout << (ans >= 0 ? ans : -1) << "\n";
	}
}
/*
6 6
1 2 3 4
1 5
5 6
6 3
6 4
1 2
3 4

7 8
1 7 4 5
4 5
1 2
1 3
2 4
3 5
4 6
5 6
6 7


 */
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...