73. 找最佳通路
★☆ 输入文件:city.in
输出文件:
city.out
简单对比
时间限制:1 s 内存限制:128 MB
问题描述
有 n 个 城市,它们之间的交通情况已知。现在要求根据一个出发点Cs和一个到达点Cd,请编程序,由计算机找到从城市Cs 到 Cd 的一条路径,要求经过城市最少。
【输入格式】
输入文件: city.in
输入由若干行组成,第一行有四个整数,n(1≤n≤50)、m(1≤m≤n*n)和s(1≤s≤n)、e(1≤e≤n);n表示城市数,m表示道路数,s和e表示出发点和到达点。
第 2至m+1行是m 条边的 信息,每行两个整数,为边的起点和终点。
【输出格式】
输出文件: city.out
一个整数,经过城市的个数(包括起点和终点)
【输入样例】
输入文件名:city.in
6 6 1 5
1 3
2 6
3 6
3 2
6 4
4 5
输出文件名:city.out
5
可以直接BFS。因为图节点少,而且没有权值。
#include<cstdio>
#include<queue>
using namespace std;
const int maxn = 110;
bool link[maxn][maxn];
int n,m,s,e;
bool vis[maxn];
struct node{
int x,step;
};
int step;
void bfs(){
node s_pos;
queue<node >q;
s_pos.x=s; s_pos.step=1;
q.push(s_pos);
vis[s]=true;
while(!q.empty()){
node x=q.front(); q.pop();
if(x.x==e){ step=x.step;return ;}
for(int i=1;i<=n;i++){
if(link[x.x][i]&&!vis[i]){
vis[i]=true;
s_pos.x=i; s_pos.step=x.step+1;
q.push(s_pos);
}
}
}
}
int main(){
freopen("city.in","r",stdin);
freopen("city.out","w",stdout);
int a,b;
scanf("%d%d%d%d",&n,&m,&s,&e);
for(int i=0;i<m;i++){
scanf("%d%d",&a,&b);
link[a][b]=true;
}
bfs(); printf("%d\n",step);
return 0;
}