首页 > 其他分享 >1135新年好

1135新年好

时间:2022-12-20 19:35:17浏览次数:55  
标签:dist cur int 1135 新年好 heap include dis

原题链接

思路

从自己家开始,顺序任意,能去五个亲戚家,可以从亲戚家去到另外的亲戚家,于是这启发我们把每个亲戚和自己到全图其他点的最短路处理出来。
这乍一看是多源汇最短路,但是我们发现\(Floyd\)算法是\(O(N^{3})\)的,在这题的条件下=根本跑不过
但是我们的源点有几个? 只有一个自己加上五个亲戚,如果做\(6\)次\(Dijkstra\),每次\(Dijkstra\)是\(O(mlogn)\)的,所以我们可以用\(Dijkstra\)

代码

#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>

using namespace std;
typedef pair<int, int> PII;

const int N = 1000010, M = 1e5 + 10, INF = 0x3f3f3f3f;
int h[N], e[M << 1], w[M << 1], ne[M << 1], idx;
int dist[6][N], rel[10], n, m;
bool st[N];

void add(int a, int b, int c)
{
    e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx ++ ;
}

void Dijkstra(int S, int dist[]) 
{
    for (int i = 0; i <= n; i ++ ) 
        dist[i] = INF;
    
    memset(st, 0, sizeof st);
    
    priority_queue<PII, vector<PII>, greater<> > heap;
    heap.push({0, S}), dist[S] = 0;
    
    while (heap.size())
    {
        auto t = heap.top().second; heap.pop();
        
        if (st[t]) continue ;
        st[t] = true;
        
        for (int i = h[t]; ~i; i = ne[i]) 
        {
            int j = e[i];
            if (dist[j] > dist[t] + w[i]) 
            {
                dist[j] = dist[t] + w[i];
                heap.push({dist[j], j});
            }
        }
    }
}

int dfs(int cur, int S, int dis)  //cur是已经访问过的亲戚,S是当前所在点,dis是这条路线的总长度
{
    if (cur == 6) return dis;
    int res = INF;
    for (int i = 1; i <= 5; i ++ ) 
    {
        if (st[i]) continue ;
        st[i] = true;
        int nx = rel[i];
        res = min(res, dfs(cur + 1, i, dist[S][nx] + dis));
        st[i] = false;
    }
    return res;
}

int main()
{
    memset(h, -1, sizeof h);
    scanf("%d%d", &n, &m);
    
    rel[0] = 1;
    for (int i = 1; i <= 5; i ++ ) 
        scanf("%d", &rel[i]);
        
    while (m -- ) 
    {
        int u, v, w;
        scanf("%d%d%d", &u, &v, &w);
        add(u, v, w), add(v, u, w);
    }
    
    for (int i = 0; i <= 5; i ++ ) Dijkstra(rel[i], dist[i]);
    
    memset(st, 0, sizeof st);
    printf("%d\n", dfs(1, 0, 0));
    
    return 0;
}

标签:dist,cur,int,1135,新年好,heap,include,dis
From: https://www.cnblogs.com/StkOvflow/p/16994922.html

相关文章

  • #10078. 「一本通 3.2 练习 4」新年好
     从1出发访问5个给定点,最小化路程 枚举5个点的排列,然后单源最短路#include<iostream>#include<cstring>#include<queue>usingnamespacestd;structT{......