图的基本存储的基本方式二——邻接表(链表)

来源:互联网 发布:scada数据采集 编辑:程序博客网 时间:2024/06/06 02:54

图的基本存储的基本方式二

Time Limit: 1000MS Memory Limit: 65536KB
Submit Statistic
Problem Description

解决图论问题,首先就要思考用什么样的方式存储图。但是小鑫却怎么也弄不明白如何存图才能有利于解决问题。你能帮他解决这个问题么?
Input

多组输入,到文件结尾。
每一组第一行有两个数n、m表示n个点,m条有向边。接下来有m行,每行两个数u、v代表u到v有一条有向边。第m+2行有一个数q代表询问次数,接下来q行每行有一个询问,输入两个数为a,b。
注意:点的编号为0~n-1,2<=n<=500000 ,0<=m<=500000,0<=q<=500000,a!=b,输入保证没有自环和重边
Output

对于每一条询问,输出一行。若a到b可以直接连通输出Yes,否则输出No。
Example Input

2 1
0 1
2
0 1
1 0
Example Output

Yes
No
Hint

Author

lin

#include<stdio.h>#include<algorithm>#include<iostream>#include<string.h>#include<math.h>#include<set>using namespace std;struct node{    int data;    struct node *next;}*p,*q,*tail,*head[500001];int main(){    int n,m,t,i,a,b,c,d;    while(cin>>n>>m)    {        int flag;        memset(head,0,sizeof(head));        for(i=0; i<m; i++)        {            cin>>a>>b;            if(head[a]==NULL)    // 建立图链表,开始时,图内无元素            {                head[a]=new node;                head[a]->data=b;                head[a]->next=NULL;            }            else            {                q=head[a]->next;   //p,q交叉向后建立起链表                p=new node;                p->data=b;                p->next=q;                head[a]->next=p;            }        }        cin>>t;        while(t--)        {            flag=0;            cin>>c>>d;        //输入询问的路线            if(head[c]==NULL)                cout<<"No"<<endl;            else            {                q=head[c];                while(q!=NULL)                {                    if(q->data==d)       //询问路是否通                    {                        flag=1;                        break;                    }                    q=q->next;                }                if(flag==1)                    cout<<"Yes"<<endl;                else cout<<"No"<<endl;            }        }    }    return 0;}/***************************************************Result: AcceptedTake time: 132msTake Memory: 3960KBSubmit time: 2017-02-16 17:02:01****************************************************/