图论基础 PTA 路径判断 && 最短路径分数

PTA

7-9 路径判断

给定一个有N个顶点和E条边的无向图,请判断给定的两个顶点之间是否有路径存在。
假设顶点从0到N−1编号。

输入格式:

输入第1行给出2个整数N(0<N≤10)和E,分别是图的顶点数和边数。

随后E行,每行给出一条边的两个端点。每行中的数字之间用1空格分隔。

最后一行给出两个顶点编号i,j(0≤i,j<N),i和j之间用空格分隔。

输出格式:

如果i和j之间存在路径,则输出"There is a path between i and j.",

否则输出"There is no path between i and j."。

输入样例1:

7 6
0 1
2 3
1 4
0 2
1 3
5 6
0 3

输出样例1:

There is a path between 0 and 3.

输入样例2:

7 6
0 1
2 3
1 4
0 2
1 3
5 6
0 6

输出样例2:

There is no path between 0 and 6.

#include<bits/stdc++.h>
using namespace std;
int a[11][11];
int b[20]={0}; 
int n,m;
queue<int>q;
void bfs(int no,int ne){
	b[no]=1;
	q.push(no);
	while(!q.empty()){
		int s=q.front();
		for(int i=0;i<n;i++){
			if(a[s][i]==1&&b[i]==0){
				b[i]=b[s]+1;
				q.push(i);
			}
		}
		q.pop();
	}
}
int main(){
	cin>>n>>m;
	while(m--){
		int no,ne;
		cin>>no>>ne;
		//记录无向图; 
		a[no][ne]=1;
		a[ne][no]=1;
	}
	int bn,en;
	cin>>bn>>en;
	bfs(bn,en);
	if(b[en]>0){
		printf("There is a path between %d and %d.\n",bn,en);
	}
	else{
		printf("There is no path between %d and %d.\n",bn,en);
	}
	return 0;
}

这算是我第一个写的图相关的题吧

7-7 最短路径

分数 20

全屏浏览题目

切换布局

作者 DS课程组

单位 临沂大学

给定一个有N个顶点和E条边的无向图,顶点从0到N−1编号。请判断给定的两个顶点之间是否有路径存在。如果存在,给出最短路径长度。
这里定义顶点到自身的最短路径长度为0。
进行搜索时,假设我们总是从编号最小的顶点出发,按编号递增的顺序访问邻接点。

输入格式:

输入第1行给出2个整数N(0<N≤10)和E,分别是图的顶点数和边数。
随后E行,每行给出一条边的两个顶点。每行中的数字之间用1空格分隔。
最后一行给出两个顶点编号i,j(0≤i,j<N),i和j之间用空格分隔。

输出格式:

如果i和j之间存在路径,则输出"The length of the shortest path between i and j is X.",X为最短路径长度,
否则输出"There is no path between i and j."。

输入样例1:

7 6
0 1
2 3
1 4
0 2
1 3
5 6
0 3

输出样例1:

The length of the shortest path between 0 and 3 is 2.

输入样例2:

7 6
0 1
2 3
1 4
0 2
1 3
5 6
0 6

输出样例2:

There is no path between 0 and 6.
#include<bits/stdc++.h>
using namespace std;
int a[11][11];
int b[20]={0}; 
int n,m;
queue<int>q;
void bfs(int no,int ne){
	b[no]=1;
	q.push(no);
	while(!q.empty()){
		int s=q.front();
		for(int i=0;i<n;i++){
			if(a[s][i]==1&&b[i]==0){
				b[i]=b[s]+1;
				q.push(i);
			}
		}
		q.pop();
	}
}
int main(){
	cin>>n>>m;
	while(m--){
		int no,ne;
		cin>>no>>ne;
		//记录无向图; 
		a[no][ne]=1;
		a[ne][no]=1;
	}
	int bn,en;
	cin>>bn>>en;
	bfs(bn,en); 
// 	for(int i=0;i<n;i++){
// 		cout<<b[i]<<" ";
// 	}
// 	cout<<"\n";
	if(b[en]>0){
		printf("The length of the shortest path between %d and %d is %d.",bn,en,b[en]-1);
	}
	else{
		printf("There is no path between %d and %d.",bn,en);
	}
	return 0;
}

 怎么说呢,这两题不压根就是一题吗。。。。。

 

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值