题目描述
blablabla
样例
blablabla
算法1
(暴力枚举) $O(n^2)$
blablabla
时间复杂度
参考文献
C++ 代码
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
typedef pair<int, int> PII;
const int N = 50010, M = 200010, INF = 0x3f3f3f3f;
int n, m;
int dist[6][N];
bool st[N];
int relation[6];
int h[N], e[M], ne[M], w[M], idx;
void add(int a, int b, int c)
{
e[idx] = b, ne[idx] = h[a], w[idx] = c, h[a] = idx ++;
}
void spfa(int source, int dist[])
{
memset(dist, 0x3f, N * 4);
queue<int> q;
q.push(source);
st[source] = true;
dist[source] = 0;
while(q.size())
{
auto t = q.front();
q.pop();
st[t] = false;
for (int i = h[t]; ~i; i = ne[i])
{
int j = e[i], d = w[i];
if (dist[j] > dist[t] + d)
{
dist[j] = dist[t] + d;
if (!st[j])
{
q.push(j);
st[j] = true;
}
}
}
}
}
void dijkstra(int source, int dist[])
{
memset(dist, 0x3f, N * 4);
memset(st, 0, sizeof st);
priority_queue<PII, vector<PII>, greater<PII>> heap;
heap.push({0, source});
dist[source] = 0;
while(heap.size())
{
auto t = heap.top();
heap.pop();
int u = t.second, d = t.first;
if (st[u]) continue;
st[u] = true;
for (int i = h[u]; ~i; i = ne[i])
{
int j = e[i];
if (!st[j] && dist[j] > d + w[i])
{
dist[j] = d + w[i];
heap.push({dist[j], j});
}
}
}
}
int dfs(int u, int last, int distance)
{
if (u == 6) return distance;
int res = INF;
for (int i = 1; i <= 5; i ++ )
{
if (!st[i])
{
st[i] = true;
int j = relation[i];
res = min(res, dfs(u + 1, i, distance + dist[last][j]));
st[i] = false;
}
}
return res;
}
int main()
{
cin >> n >> m;
for (int i = 1; i <= 5; i ++) cin >> relation[i];
relation[0] = 1;
memset(h, -1, sizeof h);
while(m --)
{
int a, b, c;
cin >> a >> b >> c;
add(a, b, c);
add(b, a, c);
}
for (int i = 0; i < 6; i ++) dijkstra(relation[i], dist[i]);
memset(st, 0, sizeof st);
cout << dfs(1, 0, 0) << endl;
return 0;
}
算法2
(暴力枚举) $O(n^2)$
blablabla
时间复杂度
参考文献
C++ 代码
blablabla
在dfs里面为什么既能return distance,又能return res,这两个不会矛盾吗