您的位置:首页 > 大数据 > 人工智能

SPOJ - ADACYCLE - Ada and Cycle - 带环最短路(BFS) - Mutual Training for Wannafly Union #7

2017-04-04 10:27 1286 查看
1.题目描述:


ADACYCLE - Ada and Cycle

no tags 

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 i and j (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


 Submit
solution!

2.题意概述:

给你邻接矩阵,其中ij元素的0表示i到j没有道路,1表示有长度为1的道路,某人喜欢短途旅行,要你判断他在i城市时候的最短旅行路程是什么,不存在则输出NO WAY

3.解题思路:

短途旅行意味着至少要经过一个城市。一种思路是用邻接表存边,对每个城市开始进行bfs,开始不对起点的vis标记,每当走到起点时候更新一下最大值。还有需要注意的是INF太小也不行,0x3f3f3f3f也wa了好几发

当时也是T到生活不能自理!!!然后是几个重要剪枝:

1.如果i城市的邻接表size是0就没必要进行bfs。

2.bfs中如果当前路线花的时间超过了当前的最小值就没必要继续入队了。

4.AC代码:

#include <bits/stdc++.h>
#define INF 0x7fffffff
#define maxn 100100
#define N 2222
#define eps 1e-6
#define pi acos(-1.0)
#define e exp(1.0)
using namespace std;
const int mod = 1e9 + 7;
typedef long long ll;
typedef unsigned long long ull;
struct node
{
int to, val;
node(int a, int b) { to = a; val = b; }
};
struct que
{
int cur;
int step;
que(int a, int b) { cur = a; step = b; }
};
vector<node> mp
;
bool vis
;
int ans;
void bfs(int sta)
{
memset(vis, 0, sizeof(vis));
queue<que> q;
q.push(que(sta, 0));
bool first = 1;
while (!q.empty())
{
que qq = q.front();
q.pop();
int u = qq.cur;
int step = qq.step;
if (first)
first = 0;
else
{
vis[u] = 1;
if (u == sta)
{
ans = min(ans, step);
continue;
}
}
int sz = mp[u].size();
for (int i = 0; i < sz; i++)
{
int v = mp[u][i].to;
int w = step + mp[u][i].val;
if (!vis[v])
{
vis[v] = 1;
if (w >= ans)
continue;
if (v == sta)
{
ans = min(ans, w);
continue;
}
q.push(que(v, w));
}
}
}
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
long _begin_time = clock();
#endif
int n;
while (~scanf("%d", &n))
{
for (int i = 1; i <= n; i++)
mp[i].clear();
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
{
int x;
scanf("%d", &x);
if (x == 1)
mp[i].push_back(node(j, 1));
}
for (int i = 1; i <= n; i++)
{
ans = INF;
if (mp[i].size())
bfs(i);
if (ans == INF)
puts("NO WAY");
else
printf("%d\n", ans);
}
}
#ifndef ONLINE_JUDGE
long _end_time = clock();
printf("time = %ld ms.", _end_time - _begin_time);
#endif
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  acm 算法 spoj