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;
}
怎么说呢,这两题不压根就是一题吗。。。。。