POJ - 1847(朴素dijkstra)

题目链接

思路:
由题意得只有第一个方向不要转距离为 0,其他方向要转距离都为 1,
已知起点和中点,朴素dijkstra即可,感觉最短路的问题很多有建图思路大概就会写了。
样例为答案为 0 的情况解释 :2 -> 3 -> 1

代码:

#include <iostream>
#include <algorithm>
#include <iostream>
#include <string>
#include <stdio.h>
#include <algorithm>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <math.h>
#include <climits>
#include <iomanip>
#include <queue>
#include <vector>
#define fastio ios::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL)
#define debug(a) cout << "debug : " << (#a) << " = " << a << endl

using namespace std;

typedef long long ll;
typedef pair<int, int> PII;

const int N = 110;
const int INF = 0x3f3f3f3f;
const double eps = 1e-6;
const int mod = 998244353;

int a[N][N];
int n, s, t;
bool vis[N];
int dis[N];

int dijkstra()
{
    memset(vis, false, sizeof vis);
    memset(dis, INF, sizeof dis);
    dis[s] = 0;
    for (int i = 1; i <= n; i++)
    {
        int t = -1;
        for (int j = 1; j <= n; j++)
        {
            if (!vis[j] && (t == -1 || dis[j] < dis[t]))
                t = j;
        }
        vis[t] = true;
        for (int j = 1; j <= n; j++)
            dis[j] = min(dis[j], dis[t] + a[t][j]);
    }
    if (dis[t] == INF)
        return -1;
    else
        return dis[t];
}

int main()
{
    memset(a, INF, sizeof a);
    cin >> n >> s >> t;
    for (int i = 1; i <= n; i++)
    {
        int k;
        cin >> k;
        for (int j = 1; j <= k; j++)
        {
            int r;
            cin >> r;
            if (j == 1)
                a[i][r] = 0;
            else
                a[i][r] = 1;
        }
    }
    cout << dijkstra() << endl;
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值