Dijkstra Sequence

Dijkstra’s algorithm is one of the very famous greedy algorithms.
It is used for solving the single source shortest path problem which gives the shortest paths from one particular source vertex to all the other vertices of the given graph. It was conceived by computer scientist Edsger W. Dijkstra in 1956 and published three years later.

In this algorithm, a set contains vertices included in shortest path tree is maintained. During each step, we find one vertex which is not yet included and has a minimum distance from the source, and collect it into the set. Hence step by step an ordered sequence of vertices, let’s call it Dijkstra sequence, is generated by Dijkstra’s algorithm.

On the other hand, for a given graph, there could be more than one Dijkstra sequence. For example, both { 5, 1, 3, 4, 2 } and { 5, 3, 1, 2, 4 } are Dijkstra sequences for the graph, where 5 is the source. Your job is to check whether a given sequence is Dijkstra sequence or not.

在这里插入图片描述

Sample Input:

5 7
1 2 2
1 5 1
2 3 1
2 4 1
2 5 2
3 5 1
3 4 1
4
5 1 3 4 2
5 3 1 2 4
2 3 4 5 1
3 2 1 5 4

Sample Output:

Yes
Yes
Yes
No

解题思路:
直接dijistra算法,每一步要求出所有距离起始点最近的点,然后判断给定的序列的第i位是否在这些点中,如果在的话就选择这个点继续执行dijkstra。如果dijkstra成功执行完,则这个序列就是对的。

#include<bits/stdc++.h>
using namespace std;
const int INF = INT_MAX;
const int maxn = 1e3+5;
int G[maxn][maxn];
int d[maxn],n,m;
int a[maxn];
bool dijistra(int x) {
	fill(d, d + maxn, INF);
    bool visited[maxn] = {false};
	d[x] = 0;
	for(int i = 1; i <= n; i++) {
		int u = -1, MIN = INF;
		for(int j = 1; j <= n; j++) {
			if(visited[j] == false && d[j] < MIN) {
				u = j;
				MIN = d[j];
			}
		}
        if(d[a[i]] == MIN) u = a[i];
		else return false;
		visited[u] = true;
		for(int v = 1; v <= n; v++) {
			if(visited[v] == false && G[u][v] != INF && d[u] + G[u][v] < d[v]) 
				d[v] = d[u] + G[u][v];
		}
	}
    return true;
} 
int main() {
	fill(G[0], G[0] + maxn * maxn, INF);
	scanf("%d%d", &n, &m);
	while(m--) {
		int u, v, w;
		scanf("%d%d%d", &u, &v, &w);
		G[v][u] = G[u][v] = min(G[u][v], w);
	}
    int q;
    scanf("%d", &q);
    while(q--) {
        for(int i = 1; i <= n; i++) {
            scanf("%d", &a[i]);
        }
        if(dijistra(a[1])) puts("Yes");
        else puts("No");
    }
	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值