Cat Snuke and a Voyage

题目描述
In Takahashi Kingdom, there is an archipelago of N islands, called Takahashi Islands. For convenience, we will call them Island 1, Island 2, ..., Island N.
There are M kinds of regular boat services between these islands. Each service connects two islands. The i-th service connects Island ai and Island bi.
Cat Snuke is on Island 1 now, and wants to go to Island N. However, it turned out that there is no boat service from Island 1 to Island N, so he wants to know whether it is possible to go to Island N by using two boat services.
Help him.

Constraints
3≤N≤200 000
1≤M≤200 000
1≤ai<bi≤N
(ai,bi)≠(1,N)
If i≠j, (ai,bi)≠(aj,bj).

输入
Input is given from Standard Input in the following format:
N M
a1 b1
a2 b2
:
aM bM

输出
If it is possible to go to Island N by using two boat services, print POSSIBLE; otherwise, print IMPOSSIBLE.

样例输入
3 2
1 2
2 3

样例输出
POSSIBLE

这个题之所以要写一下就是之前在打比赛的时候用了一个二维数组和两个嵌套的for循环,结果提交的时候老是超时,后来补提的时候参考了一下别人的代码,让自己算法优化了好多,写下来和大家分享一下

我的思路是这样的:首先开一个布尔数组,用来记录可能的中转站(存在一个岛屿可以从1号岛屿到达它或者是可以从它到达n号岛屿)的位置,如果这个中转站可以把1号和n号岛屿连接起来的话,那么答案就是可能的,否则就是不可能

#include<iostream>
using namespace std;
bool center[200001];//用来记录可能的中转站
bool flag=false;//代表是否可能,先默认为假,如果能找到沟通1和n号的中转站的话就是为真
int main(){
 int n,m;
cin>>n>>m;
	 int start,end;//定义记录起点和终点的变量
	 for(int i=1;i<=m;i++){
		 
		 cin>>start>>end;
	 if(flag)
		 continue;//如果在前面的几次数据中已经判断出可能的话,后边的数据就没有在判断的必要啦
	 if(start==1){
		 if(center[end]){/*如果看完整我的代码的话,就可以看出center【end】代表是否存在从end号岛屿到达n点的
						 中转站,如果存在的话,那么这个中转站就把1号和n号连接了起来,那么就是可能的,flag设置为true*/
		 flag=true;
		 }
		 else
		 center[end]=true;//如果没有存在的话就先把他记做可能的中转站
	 }
	 else if(end==n){
		 if(center[start]){//这里刚好和上面反过来,我就不详细的解释啦
		 flag=true;
		 }
		 else
			 center[start]=true;
	 }

	 
	 }
	 if(flag)
		 cout<<"POSSIBLE"<<endl;
	 else
		 cout<<"IMPOSSIBLE"<<endl;
	 
	 return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值