关系网络

传送门

题目描述

有 n 个人,编号为 1~n。其中有一些人相互认识,现在 x 想要认识 y,可以通过他所认识的人来认识更多的人(如果 a 认识 b、b 认识 c,那么 a 可以通过 b 来认识 c),求出 x 最少需要通过多少人才能认识 y。

输入格式

第 1 行 3 个正整数 n、x、y,其中:n≤100,1≤x、y≤n。
接下来是一个 n×n 的邻接矩阵,a[i,j]=1 表示 i 认识 j,a[i,j]=0 表示 i 不认识 j。
保证 i=j 时,a[i,j]=0,并且 a[i,j] =a[j,i],一行中的两个数之间有一个空格。

输出格式

输出一行一个数,表示 x 认识 y 最少需要通过的人数。

输入样例

5 1 5
0 1 0 0 0
1 0 1 1 0
0 1 0 1 0
0 1 1 0 1
0 0 0 1 0

输出样例

2

主要思路

这是一道Spfa模板题(单源源)

只需要把所有边权值赋为1就行了,最后再减1

特判:如果x和y是同一个人,输出0

——————————AC代码

#include<bits/stdc++.h>
using namespace std;
const int maxn=1e6+99;
int n,tot,head[maxn],vis[maxn],dis[maxn],a,x,y;
struct edge{
	int to,next,w;
}e[maxn];
void add(int a,int b,int w){
	e[++tot].to=b;
	e[tot].next=head[a];
	e[tot].w=w;
	head[a]=tot;
}
void Spfa(int x){
	memset(dis,0x3f,sizeof(dis));
	dis[x]=0;
	vis[x]=1;
	queue<int> q;
	q.push(x);
	while(!q.empty()){
		int tmp=q.front();
		q.pop();
		vis[tmp]=0;
		for(int i=head[tmp];i;i=e[i].next){
			if(dis[tmp]+e[i].w<dis[e[i].to]){
				dis[e[i].to]=dis[tmp]+e[i].w;
				if(!vis[e[i].to])q.push(e[i].to),vis[e[i].to]=1;
			}
		}
	}
}
int main(){
	cin>>n>>x>>y;
	for(int i=1;i<=n;i++)
		for(int j=1;j<=n;j++){
			cin>>a;
			if(a==1)add(i,j,1),add(j,i,1);
		}
	if(x==y){cout<<0;return 0;}
	Spfa(x);
	if(dis[y]==0x3f3f3f3f)cout<<0;
	else cout<<dis[y]-1;
	return 0;
}

——————————QAQ

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值