为什么输出0
查看原帖
为什么输出0
1237323
zhutongxuan楼主2024/11/10 12:01
/*#include<bits/stdc++.h>
#define int long long
using namespace std;
vector<int> e[200001];
int dis[200001],n,m,u,v;
queue<int> q;
signed main(){
	cin>>n>>m;
	while(m--){
		cin>>u>>v;
		e[u].push_back(v);
	}
	q.push(1);
	while(!q.empty()){
		int u=q.front();
		q.pop();
		for(int i:e[u]){
			if(dis[i]) continue;
			q.push(i);
			dis[i]=dis[u]+1;
		}
	}
	cout<<(dis[1]==0?-1:dis[1])<<endl;
	return 0;
}*/
#include<iostream>
#include<cstdio>
#include<queue>
using namespace std;
bool vis[200001];
long long m, n, s, head[200001], cnt, ans[200001], u;
struct edge {
	int to, w, next;
}edge[400001];
struct priority {
	int ans, id;
	bool operator <(const priority& x)const {
		return x.ans < ans;
	}
};
priority_queue<priority> q;
void add(int u, int v, int w) {
	edge[++cnt].to = v;
	edge[cnt].w = w;
	edge[cnt].next = head[u];
	head[u] = cnt;
}
int main() {
	cin >> n >> m;
	s = 1;
	for (int i = 1; i <= m; i++) ans[i] = 2147483647;
	ans[s] = 0;
	for (int i = 1; i <= m; i++) {
		int u, v;
		cin >> u >> v;
		add(u, v, 1);
	}
	q.push((priority) { 0, 1 });
	while (!q.empty()) {
		u = q.top().id;
		q.pop();
		if (!vis[u]) {
			vis[u] = 1;
			for (int i = head[u]; i; i = edge[i].next) if (ans[edge[i].to] > ans[u] + edge[i].w && !vis[edge[i].to]) {
				ans[edge[i].to] = ans[u] + edge[i].w;
				q.push((priority) { ans[edge[i].to], edge[i].to });
			}
		}
	}
	cout << ans[1] << endl;
	return 0;
}
2024/11/10 12:01
加载中...