[AcWing 1135] 新年好
最短路 + DFS 枚举顺序
最短路用堆优化 dijkstra 复杂度
DFS 枚举复杂度
两个复杂度是相加的关系
点击查看代码
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef pair<int,int> PII;
const int N = 1e6 + 10;
const int INF = 0x3f3f3f3f;
int n, m;
int h[N], e[N], ne[N], w[N], idx;
int d[6][N]; // 第一维是 0 ~ 5,代表的是人,而不是车站
int stop[6];
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 sp, int d[])
{
memset(d, 0x3f, sizeof st);
memset(st, false, sizeof st);
priority_queue<PII, vector<PII>, greater<PII>> heap;
heap.push({0, sp});
d[sp] = 0;
while (heap.size()) {
auto t = heap.top();
heap.pop();
auto v = t.second;
if (st[v])
continue;
st[v] = true;
for (int i = h[v]; i != -1; i = ne[i]) {
int j = e[i];
if (d[j] > d[v] + w[i]) {
d[j] = d[v] + w[i];
heap.push({d[j], j});
}
}
}
}
int dfs(int u, int start, int dist)
{
if (u > 5)
return dist;
int res = INF;
for (int i = 1; i <= 5; i ++)
if (!st[i]) {
int next = stop[i];
st[i] = true;
res = min(res, dfs(u + 1, i, dist + d[start][next]));
st[i] = false;
}
return res;
}
void solve()
{
cin >> n >> m;
stop[0] = 1;
for (int i = 1; i <= 5; i ++)
cin >> stop[i];
memset(h, -1, sizeof h);
for (int i = 0; i < m; i ++) {
int a, b, c;
cin >> a >> b >> c;
add(a, b, c);
add(b, a, c);
}
// 从 stop[i] 出发的最短路
for (int i = 0; i < 6; i ++)
dijkstra(stop[i], d[i]);
// DFS 枚举选择顺序
memset(st, false, sizeof st);
cout << dfs(1, 0, 0) << endl;
}
signed main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
solve();
return 0;
}
- 先用 次 求出从 个点(佳佳和五个亲戚)出发到其他点的最短距离,用 枚举访问亲戚的顺序,由于前面已经用 求出了最短距离,算距离时直接以 的复杂度从 数组中得到
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!