图结构练习—BFSDFS—判断可达性(BFS)

http://acm.sdut.edu.cn/sdutoj/problem.php?action=showproblem&problemid=2138

注意该图为有向图,1000个点应该最多有1000*999条边。在这跪了一下。。。

 1 #include<stdio.h>
 2 #include<string.h>
 3 #include<queue>
 4 
 5 using namespace std;
 6 
 7 const int maxn=1000002;
 8 int head[maxn],vis[maxn];
 9 int n,m,cnt;
10 struct node
11 {
12     int u;
13     int v;
14     int next;
15 } edge[maxn];
16 void add(int u,int v)
17 {
18     edge[cnt].u = u;
19     edge[cnt].v = v;
20     edge[cnt].next = head[u];
21     head[u] = cnt++;
22 }
23 int  bfs(int s)
24 {
25 
26     queue<int>q;
27     q.push(s);
28     vis[s] = 1;
29     while(!q.empty())
30     {
31         int u = q.front();
32         if (u==1)
33             return 1;
34         q.pop();
35         for (int j = head[u]; j!=-1; j = edge[j].next)
36         {
37             int v = edge[j].v;
38             if (!vis[v])
39             {
40                 vis[v] = 1;
41                 q.push(v);
42             }
43         }
44     }
45     return 0;
46 }
47 int main()
48 {
49     while(~scanf("%d%d",&n,&m))
50     {
51         int u,v;
52         cnt = 0;
53         memset(vis,0,sizeof(vis));
54         memset(head,-1,sizeof(head));
55         for (int i = 0; i < m; i ++)
56         {
57             scanf("%d%d",&u,&v);
58             add(u,v);
59         }
60         if(bfs(n))
61             printf("YES\n");
62         else
63             printf("NO\n");
64     }
65     return 0;
66 }
View Code

 

posted @ 2013-08-16 15:02  N_ll  阅读(267)  评论(0编辑  收藏  举报