N - Tram POJ - 1847

本文介绍了一道编程题目N-TramPOJ-1847,涉及从起点到终点的最短路径问题,使用Dijkstra算法求解。通过给定图结构,展示了如何利用优先队列实现从一个节点出发,寻找到达其他节点的最短边权路径。
摘要由CSDN通过智能技术生成

N - Tram POJ - 1847

题意: 从一个点出发,可以到达若干个点,到第一个点的边权为0,到其他点的边权为1,到不了为 inf ,求从起点到终点的最短路。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#include<vector>
using namespace std;
const int maxn = 110;
const int inf = 0x3f3f3f3f;
int N, A, B;

int head[maxn], cnt, dis[maxn];
bool vis[maxn];

struct edge{
	int to, next, w;
}e[maxn*maxn];

void add(int u, int v, int w) {	
	e[++cnt].next = head[u];
	e[cnt].to = v;
	e[cnt].w = w;
	head[u] = cnt;
}

typedef struct node{
	int len, ver;
} node;

bool operator < (const node &a, const node &b) {
	return a.len > b.len;
}

void dijkstra(int s) {
	dis[s] = 0;
	node ss;
	ss.len = 0, ss.ver = s;
	priority_queue<node> heap;
	heap.push(ss);
	
	while(heap.size()) {
		node now = heap.top(); heap.pop();
		int u = now.ver, dist = now.len;
		if(vis[u]) continue;
		vis[u] = 1;
		
		for(int i = head[u]; i; i = e[i].next) {
			int to = e[i].to;
			if(dis[to] > dist + e[i].w) {
				dis[to] = dist + e[i].w;
				node tmp; tmp.len = dis[to]; tmp.ver = to;
				heap.push(tmp);
			}
		}
	}
}

int main() {
//	freopen("test.in", "r", stdin);
	ios::sync_with_stdio(false);
	cin.tie(0); cout.tie(0);
	cin >> N >> A >> B;
	int k, v;
	memset(dis, inf, sizeof(dis));
	for(int i = 1; i <= N; i++) {
		cin >> k;
		for(int j = 1; j <= k; j++) {
			cin >> v;
			if(j == 1) add(i, v, 0);
			else add(i, v, 1);
		}
	}
	dijkstra(A);
	if(dis[B] != inf) cout << dis[B] << endl;
	else cout << "-1" << endl;
	return 0;
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值