题意分析
$n\leq2500$,直接 $\mathcal O\left(n^4\right)$ 肯定不行,但是也代表着 $\mathcal O\left(n^2\right)$ 量级的时间或空间复杂度是可以接受的。
因此,可以在 $\mathcal O\left(n^2\right)$ 的时间内通过 $n$ 次 BFS 求出 $\textit{can}_{i,j}$,即点 $i,j$ 之间的最短路上其他点的数量是否小于等于 $k$。
枚举 $4$ 个点不行,考虑优化——枚举 $2$ 个点,随后直接确定另外 $2$ 个点——这也是这道题的核心。
设路径为 $1\rightarrow a\rightarrow b\rightarrow c\rightarrow d\rightarrow 1$。
可以发现,这要求 $\textit{can}{1,a},\textit{can}{a,b},\textit{can}{b,c},\textit{can}{c,d},\textit{can}_{d,1}$,因此枚举 $b,c$,随后通过限制条件来确定 $a,d$。
可以对于每一个点 $x$,预处理出 $x,1$ 均能到达的点集 $V_x$,那么 $a,d$,即 $V_b,V_c$ 中点权最大的两个点。
存在的一个问题,即这两个点有可能是重复的,这是就需要选择点权次大点。
但是仍然可能与 $a,c$ 重复,因此可以将 $V_b,V_c$ 中前 $3$ 大的点拿出来组合,更新答案。
AC 代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
//#include<bits/stdc++.h>
#include<algorithm>
#include<iostream>
#include<cstring>
#include<iomanip>
#include<cstdio>
#include<string>
#include<vector>
#include<cmath>
#include<ctime>
#include<deque>
#include<queue>
#include<stack>
#include<list>
using namespace std;
typedef long long ll;
constexpr const int N=2500,M=10000,K=100;
constexpr const ll S=1e18;
int n,m,k;
vector<int>g[N+1];
ll s[N+1];
bool can[N+1][N+1];
vector<int>canList[N+1];
void bfs(int x){
queue<int>q;
q.push(x);
static int Tag,tag[N+1],dis[N+1];
Tag++;
dis[x]=-1;
tag[x]=Tag;
for(int i:g[x]){
q.push(i);
dis[i]=0;
tag[i]=Tag;
}
while(q.size()){
int u=q.front();q.pop();
can[x][u]=true;
for(int i:g[u]){
if(tag[i]!=Tag){
tag[i]=Tag;
dis[i]=-1;
}
if(dis[i]==-1&&dis[u]+1<=k){
dis[i]=dis[u]+1;
tag[i]=Tag;
q.push(i);
}
}
}
}
int main(){
/*freopen("test.in","r",stdin);
freopen("test.out","w",stdout);*/
ios::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
cin>>n>>m>>k;
for(int i=2;i<=n;i++){
cin>>s[i];
}
while(m--){
int u,v;
cin>>u>>v;
g[u].push_back(v);
g[v].push_back(u);
}
bfs(1);
can[1][1]=false;
for(int i=2;i<=n;i++){
bfs(i);
can[i][i]=false;
for(int j=2;j<=n;j++){
if(i!=j&&can[i][j]&&can[1][j]){
canList[i].push_back(j);
}
}
sort(canList[i].begin(),canList[i].end(),[](int a,int b){
return s[a]>s[b];
});
}
ll ans=-4*S-1;
for(int b=2;b<=n;b++){
for(int c=b+1;c<=n;c++){
if(!can[b][c]){
continue;
}
if(!canList[b].size()||!canList[c].size()){
continue;
}
for(int i=0;i<3&&i<canList[b].size();i++){
for(int j=0;j<3&&j<canList[c].size();j++){
int a=canList[b][i],d=canList[c][j];
if(a!=c&&a!=d&&b!=d){
ans=max(ans,s[a]+s[b]+s[c]+s[d]);
}
}
}
}
}
cout<<ans<<'\n';
cout.flush();
/*fclose(stdin);
fclose(stdout);*/
return 0;
}