P5764 [CQOI2005]新年好(最短路+暴搜)

这篇博客介绍了一种利用DFS解决预处理单源最短路问题的方法。代码中展示了如何构建图并进行Dijkstra算法的预处理,然后通过深度优先搜索找到从起点到所有点的最短路径。博客还包含了C++代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

传送门

因为只有5个点,可以dfs访问顺序。
先预处理出一号起点+五个点的单源最短路,再暴搜。
在语法上,二维数组作为函数参数的用法。。

#include <bits/stdc++.h>

using namespace std;
//-----pre_def----
const double PI = acos(-1.0);
const int INF = 0x3f3f3f3f;
typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int, int> PII;
typedef pair<double, double> PDD;
#define fir(i, a, b) for (int i = (a); i <= (b); i++)
#define rif(i, a, b) for (int i = (a); i >= (b); i--)
#define endl '\n'
#define init_h memset(h, -1, sizeof h), idx = 0;
#define lowbit(x) x &(-x)

//---------------
const int N = 5e4 + 10, M = 1e5 + 10;
int n, m;
int h[N], e[M << 1], ne[M << 1], w[M << 1], idx;
int dist[6][N];
int s[6];
bool st[N];
//最短路+dfs
void add(int a, int b, int c)
{
    e[idx] = b;
    w[idx] = c;
    ne[idx] = h[a];
    h[a] = idx++;
}

void dij(int S, int d[])
{
    priority_queue<PII, vector<PII>, greater<PII>> heap;
    memset(d, 0x3f, N * 4);
    d[S] = 0;
    memset(st, 0, sizeof st);
    heap.push({0, S});
    while (heap.size())
    {
        auto t = heap.top();
        heap.pop();
        if (st[t.second])
            continue;
        st[t.second] = 1;
        for (int i = h[t.second]; ~i; i = ne[i])
        {
            int tt = e[i];
            if (d[tt] > d[t.second] + w[i])
            {
                d[tt] = d[t.second] + w[i];
                heap.push({d[tt], tt});
            }
        }
    }
}
int dfs(int u, int S, int dep)
{
    if (u > 5)
        return dep;
    int res = INF;
    fir(i, 1, 5)
    {
        if (!st[i])
        {
            st[i] = 1;
            res = min(res, dfs(u + 1, i, dep + dist[S][s[i]]));
            st[i] = 0;
        }
    }
    return res;
}
int main()
{
#ifndef ONLINE_JUDGE
    freopen("in.txt", "r", stdin);
    freopen("out.txt", "w", stdout);
    int StartTime = clock();
#endif
    init_h;
    scanf("%d%d", &n, &m);
    s[0] = 1;
    fir(i, 1, 5) scanf("%d", &s[i]);
    fir(i, 1, m)
    {
        int a, b, c;
        scanf("%d%d%d", &a, &b, &c);
        add(a, b, c);
        add(b, a, c);
    }
    fir(i, 0, 5) //预处理出6个点的单源最短路
    {
        dij(s[i], dist[i]);
    }
    memset(st, 0, sizeof st);
    printf("%d", dfs(1, 0, 0));

#ifndef ONLINE_JUDGE
    printf("Run_Time = %d ms\n", clock() - StartTime);
#endif
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值