(最短路)SPOJ - Ada and Cycle (易)

本文介绍了一个有趣的图论问题——在Bugindia的地图上寻找从每个城市出发并回到该城市的最短路径长度。通过使用基础的广度优先搜索(BFS)算法,我们能够解决这个问题,并提供了一段实现这一算法的C++代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Ada the Ladybug is on a trip in Bugindia. There are many cities and some uni-directional roads connecting them. Ada is wondering about the shortest path, which begins in a city and ends in the same city. Since Ada likes short trips, she asked you to find the length of such path for each city in Bugindia.

Input

The first line will contain 0 < N ≤ 2000, the number of cities.

Then N lines follow, each containing N integers 0 ≤ Hij ≤ 1. One means, that there is a road between and (zero means there isn't a road).

Output

Print N lines, the length of shortest path which begins in city i and ends in city i. If the path doesn't exist, print "NO WAY" instead.

Example Input

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

Example Output

2
2
1
2
NO WAY

Example Input

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

Example Output

2
5
5
5
2

时间很宽松,因为每条边权值相同都为1,用最基础的bfs即可。

 1 #include <iostream>
 2 #include <string>
 3 #include <algorithm>
 4 #include <cstring>
 5 #include <cstdio>
 6 #include <cmath>
 7 #include <queue>
 8 #include <set>
 9 #include <map>
10 #include <list>
11 #include <stack>
12 #define mp make_pair
13 //#define INF 0x7fffffff
14 typedef long long ll;
15 typedef unsigned long long ull;
16 const int MAX=2e3+5;
17 const int INF=0x7fffffff;
18 using namespace std;
19 typedef pair<int,int> pii;
20 int n;
21 vector <int> g[MAX];
22 queue <pii> que;
23 bool vi[MAX];
24 int tem,an;
25 int bfs(int i)
26 {
27     while(!que.empty())
28         que.pop();
29     que.push(mp(0,i));
30     while(!que.empty())
31     {
32         pii y=que.front();
33         que.pop();
34         int dis=y.first,id=y.second;
35         for(int j=0;j<g[id].size();j++)
36         {
37             int to=g[id][j];
38             if(!vi[to])
39             {
40                 vi[to]=true;
41                 if(to==i)
42                     return dis+1;
43                 que.push(mp(dis+1,to));
44             }
45         }
46     }
47     return INF;
48 }
49 int main()
50 {
51     scanf("%d",&n);
52     for(int i=1;i<=n;i++)
53     {
54         for(int j=1;j<=n;j++)
55         {
56             scanf("%d",&tem);
57             if(tem)
58                 g[i].push_back(j);
59         }
60     }
61     for(int i=1;i<=n;i++)
62     {
63         an=INF;
64         if(g[i].size())
65         {
66             memset(vi,false,n+1);
67             an=bfs(i);
68         }
69         if(an==INF)
70             printf("NO WAY\n");
71         else
72             printf("%d\n",an);
73     }
74 }

 

转载于:https://www.cnblogs.com/quintessence/p/6676147.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值