59E - Shortest Path - CodeForces Solution


graphs shortest paths *2000

Please click on ads to support us..

C++ Code:

#include<iostream>
#include<set>
#include<queue>
#include<map>
#include<utility>
#include<vector>
#include<algorithm>
#include<iomanip>
#include<string.h>
using namespace std;
#define int long long
const int INF=1e15;
const int mod=1e9 + 7;
int gcd(int a, int b)
{
	if (a == 0)
		return b;
	return gcd(b % a, a);
}
const int N=3001;
set<pair<int,int> >  bad[3001];
vector<int> adj[N];
void solve(){
	int n,m,k;
	cin>>n>>m>>k;
	for(int i=0;i<m;i++){
		int a,b;
		cin>>a>>b;
		adj[a].push_back(b);
		adj[b].push_back(a);
	}
	for(int i=0;i<k;i++){
		int a,b,c;
		cin>>a>>b>>c;
		bad[c].insert(make_pair(a,b));
	}

	int p[n+1][n+1];

	p[1][1]=0;
	bool flag =0;
	vector<vector<int> > d(n+1,vector<int> (n+1,-1));
	d[1][1]=0;
	queue<pair<int,int> > q;
	pair<int,int> ans;
	q.push(make_pair(1,1));
	while(!q.empty()){
		pair<int,int> u=q.front();
		q.pop();
		if(u.second==n){
			flag=1;
			ans=u;
			break;
		}
		for(int v : adj[u.second]){
			if(bad[v].count(u)!=0){
				continue;
			}
			if(d[u.second][v]==-1){
				d[u.second][v]=d[u.first][u.second]+1;
				p[u.second][v]=u.first;
				q.push(make_pair(u.second,v));
			}
		}
	}
	if(!flag){
		cout<<-1<<endl;
		return;
	}
	cout<<d[ans.first][ans.second]<<endl;
	vector<int> aa;
	int v=n;
	int pp=ans.first;
	while(v!=1){
		aa.push_back(v);
		v=pp;
		pp=p[pp][aa[aa.size()-1]];
	}
	reverse(aa.begin(),aa.end());
	cout<<1<<" ";
	for(int x : aa){
		cout<<x<<" ";
	}
}
signed main()
{
	ios_base::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	int t=1;
	// cin>>t;
	while(t--){
		solve();
	}
}


Comments

Submit
0 Comments
More Questions

152. Maximum Product Subarray
337. House Robber III
869. Reordered Power of 2
1593C - Save More Mice
1217. Minimum Cost to Move Chips to The Same Position
347. Top K Frequent Elements
1503. Last Moment Before All Ants Fall Out of a Plank
430. Flatten a Multilevel Doubly Linked List
1290. Convert Binary Number in a Linked List to Integer
1525. Number of Good Ways to Split a String
72. Edit Distance
563. Binary Tree Tilt
1306. Jump Game III
236. Lowest Common Ancestor of a Binary Tree
790. Domino and Tromino Tiling
878. Nth Magical Number
2099. Find Subsequence of Length K With the Largest Sum
1608A - Find Array
416. Partition Equal Subset Sum
1446. Consecutive Characters
1618A - Polycarp and Sums of Subsequences
1618B - Missing Bigram
938. Range Sum of BST
147. Insertion Sort List
310. Minimum Height Trees
2110. Number of Smooth Descent Periods of a Stock
2109. Adding Spaces to a String
2108. Find First Palindromic String in the Array
394. Decode String
902. Numbers At Most N Given Digit Set