最短路+暴力,暴力BFS求任意两点间的短路,然后暴力枚举哪一段是公共的
import java.util.*;
import java.math.*;
public class CF543B{
final int maxn=3100;
final int INF=10000;
int n,m;
int[][] dp = new int[maxn][maxn];
int s1,t1,l1;
int s2,t2,l2;
boolean[] vis;
/***************Add_Edge**********************/
class Edge{
int to,next;
}
Edge[] edge = new Edge[maxn*maxn];
int[] Adj=new int[maxn];
int Size=0;
void init(){
for(int i=0;i<=n+10;i++) Adj[i]=-1;
Size=0;
}
void AddEdge(int u,int v){
edge[Size]=new Edge();
edge[Size].to=v;
edge[Size].next=Adj[u];
Adj[u]=Size++;
}
/***************Add_Edge**********************/
void BFS(int x){
vis=new boolean[n+10];
vis[x]=true;
Queue<Integer> q = new LinkedList<Integer>();
q.add(Integer.valueOf(x));
while(q.isEmpty()==false){
int u=q.poll();
for(int i=Adj[u];i!=-1;i=edge[i].next){
int v=edge[i].to;
if(vis[v]==true) continue;
vis[v]=true;
dp[x][v]=dp[x][u]+1;
q.add(v);
}
}
}
CF543B(){
Scanner in = new Scanner(System.in);
n=in.nextInt(); m=in.nextInt();
init();
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
dp[i][j]=INF;
}
dp[i][i]=0;
}
for(int i=0;i<m;i++){
int u,v;
u=in.nextInt(); v=in.nextInt();
dp[u][v]=dp[v][u]=1;
AddEdge(u,v);AddEdge(v,u);
}
s1=in.nextInt(); t1=in.nextInt(); l1=in.nextInt();
s2=in.nextInt(); t2=in.nextInt(); l2=in.nextInt();
for(int i=1;i<=n;i++){
BFS(i);
}
if(dp[s1][t1]>l1||dp[s2][t2]>l2){
System.out.println(-1);
return ;
}
int ans=m-dp[s1][t1]-dp[s2][t2];
for(int m1=1;m1<=n;m1++){
for(int m2=1;m2<=n;m2++){
if(m1==m2) continue;
if(dp[s1][m1]+dp[m1][m2]+dp[t1][m2]<=l1&&dp[s2][m1]+dp[m1][m2]+dp[t2][m2]<=l2)
ans=Math.max(ans,m-dp[s1][m1]-dp[s2][m1]-dp[m1][m2]-dp[t1][m2]-dp[t2][m2]);
if(dp[t1][m1]+dp[m1][m2]+dp[s1][m2]<=l1&&dp[s2][m1]+dp[m1][m2]+dp[t2][m2]<=l2)
ans=Math.max(ans,m-dp[t1][m1]-dp[s2][m1]-dp[m1][m2]-dp[s1][m2]-dp[t2][m2]);
}
}
System.out.println(ans);
}
public static void main (String[] args) {
new CF543B();
}
}