题目描述
最短路
我们可以枚举二进制状态S表示每个数是否可以出现。
由于末位已经确定是an,所以可以得到最后是否一定是2或5的倍数,因此二进制状态无需枚举2和5。
假如知道一定是2的倍数,那么根据其是否是3的倍数可知其是否是6的倍数,因此二进制状态无需枚举6。
是4的倍数只要末两位是4的倍数即可,而最后一位确定,因此我们只需要保留倒数第二位模2的结果。
这样,需要2^3枚举二进制状态,然后f[i,j,k,l]表示走到节点i此时模3余j倒数第二位模2余k此时模7余l所需最少代价。这个不能DP因为要后效性,但我们可以用最短路来跑。
为了省时间,例如如果二进制状态不包含3,那么3的那一维可以无需维护。
#include<cstdio>
#include<algorithm>
#define fo(i,a,b) for(i=a;i<=b;i++)
using namespace std;
const int maxn=100+10,maxm=10000+10,maxd=10000;
int a[maxn],f[maxn][3][2][7],dl[maxd+10][4],h[maxn],go[maxm*2],next[maxm*2];
bool bz[maxn][3][2][7],pd[10];
int i,j,k,l,t,n,m,tot,ans,ca;
bool two,five;
void add(int x,int y){
go[++tot]=y;
next[tot]=h[x];
h[x]=tot;
}
void mark(int x){
bz[dl[x][0]][dl[x][1]][dl[x][2]][dl[x][3]]^=1;
}
void solve(bool three,bool four,bool seven){
if (!two&&four) return;
int i,j,r,s,t,k,l;
pd[1]=1;
pd[2]=two;
pd[3]=three;
pd[6]=two&three;
pd[4]=pd[2]&four;
pd[5]=five;
pd[7]=seven;
if (!pd[a[1]]||!pd[a[n]]) return;
fo(i,1,n)
fo(j,0,2)
fo(k,0,1)
fo(l,0,6)
f[i][j][k][l]=1<<30;
k=0;l=1;
dl[1][0]=1;
dl[1][1]=three?a[1]%3:0;
dl[1][2]=0;
dl[1][3]=seven?a[1]%7:0;
mark(1);
f[1][three?a[1]%3:0][0][seven?a[1]%7:0]=a[1];
while (k!=l){
k=k%maxd+1;
i=dl[k][0];j=dl[k][1];r=dl[k][2];s=dl[k][3];
t=h[i];
while (t){
if (pd[a[go[t]]]&&f[i][j][r][s]+a[go[t]]<f[go[t]][three?(j+a[go[t]])%3:0][four?a[i]%2:0][seven?(s*10+a[go[t]])%7:0]){
f[go[t]][three?(j+a[go[t]])%3:0][four?a[i]%2:0][seven?(s*10+a[go[t]])%7:0]=f[i][j][r][s]+a[go[t]];
if (!bz[go[t]][three?(j+a[go[t]])%3:0][four?a[i]%2:0][seven?(s*10+a[go[t]])%7:0]){
l=l%maxd+1;
dl[l][0]=go[t];
dl[l][1]=three?(j+a[go[t]])%3:0;
dl[l][2]=four?a[i]%2:0;
dl[l][3]=seven?(s*10+a[go[t]])%7:0;
mark(l);
}
}
t=next[t];
}
mark(k);
}
if (four){
if (a[n]%4==0) k=0;else k=1;
}
else k=0;
ans=min(ans,f[n][0][k][0]);
}
int main(){
//freopen("path.in","r",stdin);freopen("path.out","w",stdout);
scanf("%d",&ca);
while (ca--){
scanf("%d%d",&n,&m);
tot=0;
fo(i,1,n) h[i]=0;
fo(i,1,n) scanf("%d",&a[i]);
if (a[n]%2==0) two=1;else two=0;
if (a[n]%5==0) five=1;else five=0;
fo(i,1,m){
scanf("%d%d",&j,&k);
add(j,k);
add(k,j);
}
ans=1<<30;
fo(i,0,1)
fo(j,0,1)
fo(k,0,1)
solve(i,j,k);
if (ans==1<<30) printf("-1\n");else printf("%d\n",ans);
}
}