you have a DAG (direct acyclic graph) with n nodes and m edge. You are standing on node 1 at the begining and you want to move the nodes to the node n and maximaze the union path edge weight.
In one move, you could move any node to a position as long as their id difference is less than or equal to l. You could only move two nodes together if they have the same destination.
Partial credit:
$O(n!)
$$ dp[i][j][k] = \left\{
\begin{aligned}
&dp[i+(1<<v_{j})][v_{j}][k]& \\
&dp[i+(1<<v_{k})][j][v_{k}]& \\
&dp[i+(1<<v_{j,k})][v_{j,k}][v_{j,k}]&
\end{aligned}
\right.
$$
$O(2^n \times n^2)
$O(n\times2^l \times l^2)
So, in this case, record $dp[i][j][k]$ where $i$ is the bit between nodes, $j$ is the smaller node, and $k$ means the bigger node's id is $j+kO(n \times 2^l \times l)
transition:
$ curr = j + highbit[i]
\begin{aligned}
&dp[i][j+(1<<v)] \space\{v-i \le l\}&\\
&dp[v][(j>>(i-v))|1] \space \{v<curr\} &\\
&dp[curr][(j>>(curr-i)) + (1<<(v-curr))] \space \{ 0\le v-curr \le l\}&\\
&dp[v][1] \{i \to v\space \&\&\space curr \to v\}&
\end{aligned}
\right.
we could use rolling array to reduce space complexity. In this problem it is not necessary, but it can reduce 400 times the memory and no change in the time complexity.
code:
```
#include <iostream>
#include <unordered_map>
#include <algorithm>
#include <vector>
#include <fstream>
#include <cstring>
#include <vector>
using namespace std;
const int MAXN = 5e3+5;
const int MAXL = 13;
unordered_map<int,unordered_map<int,bool> > mp;
int n,m,l,pos[MAXN],dp[MAXL][(1<<MAXL)+5],top[(1<<MAXL)+5],big[MAXN],ans,now;
vector<int> adj[MAXN],num;
inline int max(int a, int b) {return a>b?a:b;}
int main(){
cin >> n >> m >> l;
for (int i=1;i<=n;i++) cin >> pos[i];
for (int i=1;i<=m;i++){
int a,b; cin >> a >> b; if (!mp[a][b]) mp[a][b] = true,adj[a].push_back(b);
}
memset(top,0xff,sizeof(top));
for (int i=1;i<(1<<(l+1));i++){
for (int k=l+1;k>=0;k--){
if ((i>>k) & 1) {top[i] = k; break;}
}
}//prefix
memset (dp,0xff,sizeof(dp));
for (int i=1;i<=n;i++){
now = (i-1)%MAXL;//current now id
dp[now][1] = max(dp[now][1],big[i]);//first ensure the array is maximize.
for (int j=1;j<(1<<(l+1));j++){
int pos1 = i;
int pos2 = i+top[j];
if (dp[now][j]==-1) continue;
for (int v : adj[pos2]){
if (mp[pos1][v]) big[v] = max(big[v],dp[now][j]+pos[v]);
if (v-i>l)continue;
int nxt = j+(1<<(v-pos1));
dp[now][nxt] = max(dp[now][nxt],dp[now][j]+pos[v]);
}
for (int v : adj[pos1]){
if (v-pos2>l) continue;
if (v>pos2){
int nxt = (j>>(pos2-pos1)) + (1<<(v-pos2));
int to = (pos2-1)%MAXL;
dp[to][nxt] = max(dp[to][nxt],dp[now][j]+(((j>>(v-pos1)) & 1) ? 0 : pos[v]));
}else{
int nxt = (j>>(v-pos1))|1;
int to = (v-1)%MAXL;
dp[to][nxt] = max(dp[to][nxt],dp[now][j]+(((j>>(v-pos1)) & 1) ? 0 : pos[v]));
}
}
if (i!=n)dp[now][j] = -1; //rolling array, do not change node n though.
}
}
cout << dp[(n-1)%MAXL][1] << endl;
}
```