SSLOJ1194 最优换乘&P5767

Description

H城是一个旅游胜地,每年都有成千上万的人前来观光。为方便游客,巴士公司在各个旅游景点及宾馆,饭店等地都设置了巴士站并开通了一些单程巴上线路。每条单程巴士线路从某个巴士站出发,依次途经若干个巴士站,最终到达终点巴士站。

一名旅客最近到H城旅游,他很想去S公园游玩,但如果从他所在的饭店没有一路已士可以直接到达S公园,则他可能要先乘某一路巴士坐几站,再下来换乘同一站台的另一路巴士, 这样换乘几次后到达S公园。

现在用整数1,2,…N 给H城的所有的巴士站编号,约定这名旅客所在饭店的巴士站编号为1…S公园巴士站的编号为N。

写一个程序,帮助这名旅客寻找一个最优乘车方案,使他在从饭店乘车到S公园的过程中换车的次数最少。

Input

输入的第一行有两个数字M和N(1<=M<=100 1

Output

输出文件只有一行。如果无法乘巴士从饭店到达S公园,则输出"N0",否则输出你的程序所找到的最少换车次数,换车次数为0表示不需换车即可到达•

Sample Input

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

Sample Output

思路

一看这破题的输入就是*()&¥……#剧毒
然后我们搞定输入直接bfs。
code:

#include<cstdio>
#include<algorithm>
#include<cmath>
#include<iostream>
#include<queue>
#include<string>
using namespace std;
int m,n,v,u;
bool a[501][501],b[501];
string oo;
struct f{
 int x,y;
} o,o2;
queue<f> p;
int p2[501],l;
void bfs()
{
 while (p.size())
 {
  o=p.front();
  p.pop();
  for (int i=1;i<=n;i++)
  {
   if (a[o.x][i]==1)
   {
    o2.x=i,o2.y=o.y+1;
    if (o2.x==n)
    {
     cout<<o2.y;//一旦找到直接输出
     return;
    }
     p.push(o2);//直接插入队列,管他去不去重
   }
  }
 }
 cout<<"NO";
 return;
}
int main()
{
 scanf("%d%d\n",&m,&n);
 for (int i=1;i<=m;i++)
 {
  int u=0;
  l=0;
  scanf("%d",&p2[l++]);
  char c=getchar();
  while (c==' ')
  {
   scanf("%d",&p2[l++]);
   c=getchar();
  }//剧毒输入
  for (int i=0;i<l;i++)
  {
   for (int j=i+1;j<l;j++) a[p2[i]][p2[j]]=1;//邻接矩阵建边
  }
 }
 o.x=1,o.y=0;
 b[1]=1;
 p.push(o);
 for (int i=1;i<=n;i++) if (a[1][i])
 {
  o.x=i,o.y=0;
  b[i]=1;
  p.push(o);
 }
 bfs();
 return 0;
}

去重+普通版本(非STL)

#include<cstdio>
#include<algorithm>
#include<cmath>
#include<iostream>
#include<queue>
#include<string>
using namespace std;
int m,n,v,l,r,u;
bool a[501][501],b[501];
string oo;
struct f{
 int x,y;
} o,o2;
f p[500*500+10];
int p2[501];
void bfs()
{
 while (l<r)
 {
  o=p[l++];
  for (int i=1;i<=n;i++)
  {
   if (a[o.x][i]==1&&b[i]==0)
   {
    o2.x=i,o2.y=o.y+1;
    if (o2.x==n)
    {
     cout<<o2.y;
     return;
    }
    b[i]=1;
    p[r++]=o2;
   }
  }
 }
 cout<<"NO";
 return;
}
int main()
{
 scanf("%d%d\n",&m,&n);
 for (int i=1;i<=m;i++)
 {
  int u=0;
  l=0;
  scanf("%d",&p2[l++]);
  char c=getchar();
  while (c==' ')
  {
   scanf("%d",&p2[l++]);
   c=getchar();
  }
  for (int i=0;i<l;i++)
  {
   for (int j=i+1;j<l;j++) a[p2[i]][p2[j]]=1;
  }
 }
 l=0;
 o.x=1,o.y=0;
 b[1]=1;
 p[r++]=o;
 for (int i=1;i<=n;i++) if (a[1][i])
 {
  o.x=i,o.y=0;
  b[i]=1;
  p[r++]=o;
 }
 bfs();
 return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值