CF543B Destroying Roads 枚举 + 思维 + BFS
Code:
#include <bits/stdc++.h> #define ll long long #define setIO(s) freopen(s".in","r",stdin) #define maxn 3002 using namespace std; queue<int>Q; vector<int>G[maxn]; int n,m,s1,t1,l1,s2,t2,l2; int vis[maxn],d[maxn][maxn]; void bfs(int s) { memset(vis,0,sizeof(vis)); d[s][s]=0,vis[s]=1,Q.push(s); while(!Q.empty()) { int u=Q.front(); Q.pop(); for(int i=0;i<G[u].size();++i) { int v=G[u][i]; if(!vis[v]) { vis[v]=1,d[s][v]=d[s][u]+1; Q.push(v); } } } } int main() { // setIO("input"); scanf("%d%d",&n,&m); for(int i=1;i<=m;++i) { int a,b; scanf("%d%d",&a,&b); G[a].push_back(b), G[b].push_back(a); } memset(d,0x3f,sizeof(d)); for(int i=1;i<=n;++i) d[i][i]=0; for(int i=1;i<=n;++i) bfs(i); scanf("%d%d%d%d%d%d",&s1,&t1,&l1,&s2,&t2,&l2); if(d[s1][t1] > l1 || d[s2][t2] > l2) printf("-1\n"); else { int ans=d[s1][t1] + d[s2][t2]; for(int i=1;i<=n;++i) for(int j=1;j<=n;++j) { if(d[s1][i]+d[i][j]+d[j][t1]<=l1 && d[s2][i]+d[i][j]+d[j][t2]<=l2) { ans=min(ans, d[s1][i]+d[s2][i]+d[i][j]+d[j][t1]+d[j][t2]); } } swap(s1,t1); for(int i=1;i<=n;++i) for(int j=1;j<=n;++j) { if(d[s1][i]+d[i][j]+d[j][t1]<=l1 && d[s2][i]+d[i][j]+d[j][t2]<=l2) { ans=min(ans, d[s1][i]+d[s2][i]+d[i][j]+d[j][t1]+d[j][t2]); } } printf("%d\n",m-ans); } return 0; }