首页 > 学院 > 开发设计 > 正文

图的存储二

2019-11-08 02:13:29
字体:
来源:转载
供稿:网友


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

Time Limit: 1000MS Memory Limit: 65536KB SubmitStatistic

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 10 120 11 0

Example Output

YesNo

#include <iostream>#include <stdlib.h>#include <string.h>#include <stdio.h>using namespace std;

struct node{    int data;    struct node * next;};

int main(){    ios::sync_with_stdio(false);

    int m, n;    struct node * head[500001], *p, *temp;

    while(cin >> n >> m)    {        for(int i = 0; i < n; i++)            head[i] = NULL;//初始化链表头,对应每个点都有一个链表

        for(int i = 0; i < m; i++)//输入两点,确定连线        {            int u, v;            cin >> u >> v;            //当输入的点还没有建立链表的时候,开辟内存,存入数据            if(head[u] == NULL)            {                head[u] = (struct node *)malloc(sizeof(struct node));                head[u]->data = v;                head[u]->next = NULL;            }            //当输入的点已经开辟了内存建立了链表,通过逆序建立链表的方法,存入数据            else            {                temp = head[u]->next;                p = (struct node *)malloc(sizeof(struct node));                p->data = v;                p->next = temp;                head[u]->next = p;            }        }        int q;        cin >> q;        for(int i = 0; i < q; i++)        {            int x, y;            int flag = 0;            cin >> x >> y;            //当输入数据没有建立链表则不能连通            if(head[x] == NULL)                cout << "No" << endl;            else            {                //从当前点开始遍历整个链表,当遇到输入的数据的时候,flag赋值跳出                temp = head[x];                while(temp != NULL)                {                    if(temp->data == y)                    {                        flag = 1;                        break;                    }                    temp = temp->next;                }                if(flag == 1)                    cout << "Yes" << endl;                else                    cout << "No" << endl;            }        }    }    return 0;}


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表