6585: Cat Snuke and a Voyage
时间限制: 1 Sec 内存限制: 128 MB
提交: 202 解决: 86
[提交] [状态] [讨论版] [命题人:admin]
题目描述
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
来源/分类
题意:有很多小岛,编号1,2,3....,某两个岛之间有船可以到达,每次从1号出发,第一个数字是要到达的岛屿,第二个数字是有m个岛之间有船可以连通,接下来m行表示某两个岛连通.规定只能做两次船,问是否能到达目的岛屿
解析:两种方法.dfs搜索或者判断1的下一个结点和n的上一个结点是否有公共的就行了
AC代码(dfs):
#include<bits/stdc++.h>
using namespace std;
int cnt=0;
int head[200010];
int n,m;
struct Edge
{
int from,to,next;
} edge[200010];
int dfs(int s,int t,int k)
{
if(s==n&&k==2)
return 1;
for(int i=head[s]; i!=-1; i=edge[i].next)
{
int to=edge[i].to;
if(dfs(to,n,k+1))
return 1;
}
return 0;
}
int main()
{
int d,k;
while(~scanf("%d%d",&n,&m))
{
memset(head,-1,sizeof(head));
int u,v;
for(int i=1; i<=m; i++)
{
scanf("%d%d",&u,&v);
edge[cnt].from=u;
edge[cnt].to=v;
edge[cnt].next=head[u];
head[u]=cnt++;
}
if(dfs(1,n,0))
printf("POSSIBLE\n");
else printf("IMPOSSIBLE\n");
}
return 0;
}
AC代码(判断公共点)
#include<bits/stdc++.h>
using namespace std;
int vis[200010];
int flag;
int n,m;
int main()
{
while(~scanf("%d%d",&n,&m))
{
flag=0;
int u,v;
for(int i=1; i<=n; i++)
vis[i]=0;
for(int i=1; i<=m; i++)
{
scanf("%d%d",&u,&v);
if(flag)
continue;
if(u==1)
{
if(vis[v])
{
flag=1;
}
vis[v]=1;
}
else if(v==n)
{
if(vis[u])
{
flag=1;
}
vis[u]=1;
}
}if(flag)
printf("POSSIBLE\n");
else printf("IMPOSSIBLE\n");
}
return 0;
}