【NOIP模擬賽】圖

在這裏插入圖片描述
題解:
這道題先考慮會有幾種情況,顯然只有兩種對吧1ab一組cd一組2全部一組,那麼我們就先跑n遍bfs那麼就可以求出任意兩點間距離,然後呢就枚舉ab和cd兩組間重合長度,重合就可以減去嘛

#include<bits/stdc++.h>
using namespace std;
int n,m;
int tot,inf;
int ver[6005];
int head[6005];
int next[6005];
int vis[3005];
int f[3005][3005];
int a,b,c,d;
int read() {
	int num=0,f=1;
	char ch=getchar();
	while(ch>'9'||ch<'0') {
		if(ch=='-') f=-1;
		ch=getchar();
	}
	while(ch>='0'&&ch<='9') {
		num=(num<<3)+(num<<1)+ch-'0';
		ch=getchar();
	}
	return num;
}
void add(int x,int y) {
	ver[++tot]=y;
	next[tot]=head[x];
	head[x]=tot;
}
void bfs(int u) {
	for(int i=1; i<=n; i++) {
		vis[i]=0;
	}
	queue<int>q;
	while(q.size()) q.pop();
	q.push(u);
	vis[u]=1;
	while(q.size()) {
		int x=q.front();
		q.pop();
		for(int i=head[x]; i; i=next[i]) {
			if(!vis[ver[i]]) {
				vis[ver[i]]=1;
				q.push(ver[i]);
				f[u][ver[i]]=f[u][x]+1;
			}
		}
	}
}
int work(int x,int l,int r) {
	return min(f[x][l],f[x][r]);
}
int main() {
	n=read(),m=read();
	a=read(),b=read(),c=read(),d=read();
	for(int i=1; i<=m; i++) {
		int x=read(),y=read();
		add(x,y);
		add(y,x);
	}
	for(int i=1; i<=n; i++) bfs(i);
	int ans=f[a][b]+f[c][d];
	for(int i=1; i<=n; i++) {
		for(int j=i+1; j<=n; j++) {
			ans=min(ans,work(a,i,j)+work(b,i,j)+work(c,i,j)+work(d,i,j)+f[i][j]);
		}
	}
	printf("%d",ans);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章