20分求助
查看原帖
20分求助
983702
lrj3247楼主2024/10/2 12:02

参考了第一篇题解

#include <bits/stdc++.h>
using namespace std;
const int N=3015;
int n,m,x,y,s1,t1,s2,t2,dis1[N],dis2[N],dis3[N];
bool vis[N];
vector <int> e[N];
inline int read(){
	char ch=getchar();
	int w=0,f=1;
	while (ch<'0'||ch>'9'){
		if(ch=='-') f=-1;
		ch=getchar();
	}
	while('0'<=ch&&ch<='9'){
		w=w*10+ch-'0';
		ch=getchar();
	}
	return w*f;
}
void bfs1(){
	memset(vis,0,sizeof(vis));
	memset(dis1,0x3f,sizeof(dis1));
	queue <int> q;
	q.push(1);
	vis[1]=1,dis1[1]=0;
	while(!q.empty()){
		int now=q.front();
		q.pop();
		int len=e[now].size();
		for(int i = 0 ; i<len ; i++){
			int to=e[now][i];
			if(!vis[to]){
				vis[to]=1;
				dis1[to]=dis1[now]+1;
				q.push(to);
			}
		}
	}
}
void bfs2(){
	memset(vis,0,sizeof(vis));
	memset(dis2,0x3f,sizeof(dis2));
	queue <int> q;
	q.push(s1);
	vis[s1]=1,dis2[s1]=0;
	while(!q.empty()){
		int now=q.front();
		q.pop();
		int len=e[now].size();
		for(int i = 0 ; i<len ; i++){
			int to=e[now][i];
			if(!vis[to]){
				vis[to]=1;
				dis2[to]=dis2[now]+1;
				q.push(to);
			}
		}
	}
}
void bfs3(){
	memset(vis,0,sizeof(vis));
	memset(dis3,0x3f,sizeof(dis3));
	queue <int> q;
	q.push(s2);
	vis[s2]=1,dis3[s2]=0;
	while(!q.empty()){
		int now=q.front();
		q.pop();
		int len=e[now].size();
		for(int i = 0 ; i<len ; i++){
			int to=e[now][i];
			if(!vis[to]){
				vis[to]=1;
				dis3[to]=dis3[now]+1;
				q.push(to);
			}
		}
	}
}
int main(){
	//n=read(),m=read();
	cin>>n>>m;
	for(int i = 1 ; i<=m ; i++){
		//x=read(),y=read();
		cin>>x>>y;
		e[x].push_back(y),e[y].push_back(x);
	}
	cin>>s1>>t1>>s2>>t2;
	bfs1();
	if(dis1[s1]>t1||dis1[s2]>t2){
		cout<<-1;
		return 0;
	}
	bfs2();
	bfs3();
	int ans=1e9+15;
	for(int i = 1 ; i<=n ; i++){
		if(dis1[i]+dis2[i]+dis3[i]<ans) ans=dis1[i]+dis2[i]+dis3[i];
	}
	cout<<m-ans;
	return 0;
}
2024/10/2 12:02
加载中...