二刷,好题(因为我会做
别怂,直接干,尤其是dfs,边码边想,在纸上边写边思考没有在电脑上边码边思考快
#include<bits/stdc++.h>
typedef long long ll;
using namespace std;
const int N = 5e4 + 100;
const int M = 2e5 + 10;
int n, m;
int h[N], ne[M], e[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 ++ ;
}
int dis[10][N], pos[N];
bool st[N];
void dij(int t, int bg)
{
memset(st, 0, sizeof st);
dis[t][bg] = 0;
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<> > q;
q.push({dis[t][bg], bg});
while(q.size())
{
auto [x, u] = q.top();
q.pop();
if(st[u]) continue;
st[u] = 1;
for (int i = h[u]; ~i; i = ne[i])
{
int j = e[i];
if(dis[t][j] > dis[t][u] + w[i])
{
q.push({dis[t][j] = dis[t][u] + w[i], j});
}
}
}
}
int ans = 0x3f3f3f3f;
int a[10];
bool used[10];
void dfs(int num)
{
if(num == 5) { // 0 1 2 3 4
int sum = 0;
sum += dis[1][pos[a[0]]];
for (int i = 0; i <= 3; i ++ ) {
sum += dis[a[i]][pos[a[i + 1]]];
}
ans = min(ans, sum);
return;
}
for (int i = 2; i <= 6; i ++ ) {
if(!used[i])
{
used[i] = 1;
a[num] = i;
dfs(num + 1);
used[i] = 0;
}
}
}
int main(){
//std::ios::sync_with_stdio(false);
//std::cin.tie(nullptr);
memset(h, -1, sizeof h);
memset(dis, 0x3f, sizeof dis);
cin >> n >> m;
for (int i = 2; i <= 6; i ++ ) {
cin >> pos[i];
}
while(m -- ) {
int a, b, c;
cin >> a >> b >> c;
add(a, b, c), add(b, a, c);
}
dij(1, 1);
for (int i = 2; i <= 6; i ++ ) {
dij(i, pos[i]);
}
dfs(0);
cout << ans <<'\n';
return 0;
}
STL提供了两个用来计算排列组合关系的算法,分别是next_permutation和prev_permutation。首先我们必须了解什么是“下一个”排列组合,什么是“前一个”排列组合
next_permutation()会取得[first,last)所标示之序列的下一个排列组合,如果没有下一个排列组合,便返回false;否则返回true。
next_permutation会根据你给定的数组开始输出排列,所以你一开始要想从哪开始求下一个排列
其算法思想如下:
#include<bits/stdc++.h>
typedef long long ll;
using namespace std;
const int N = 5e4 + 100;
const int M = 2e5 + 10;
int n, m;
int h[N], ne[M], e[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 ++ ;
}
int dis[10][N], pos[N];
bool st[N];
void dij(int t, int bg)
{
memset(st, 0, sizeof st);
dis[t][bg] = 0;
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<> > q;
q.push({dis[t][bg], bg});
while(q.size())
{
auto [x, u] = q.top();
q.pop();
if(st[u]) continue;
st[u] = 1;
for (int i = h[u]; ~i; i = ne[i])
{
int j = e[i];
if(dis[t][j] > dis[t][u] + w[i])
{
q.push({dis[t][j] = dis[t][u] + w[i], j});
}
}
}
}
int ans = 0x3f3f3f3f;
int a[10] = {2,3,4,5,6};
int main(){
//std::ios::sync_with_stdio(false);
//std::cin.tie(nullptr);
memset(h, -1, sizeof h);
memset(dis, 0x3f, sizeof dis);
cin >> n >> m;
for (int i = 2; i <= 6; i ++ ) {
cin >> pos[i];
}
while(m -- ) {
int a, b, c;
cin >> a >> b >> c;
add(a, b, c), add(b, a, c);
}
dij(1, 1);
for (int i = 2; i <= 6; i ++ ) {
dij(i, pos[i]);
}
do
{
int sum = 0;
sum += dis[1][pos[a[0]]];
for (int i = 0; i <= 3; i ++ ) {
sum += dis[a[i]][pos[a[i + 1]]];
}
ans = min(ans, sum);
} while (next_permutation(a, a + 5));
cout << ans <<'\n';
return 0;
}