图的存储二

来源:互联网 发布:大数据 云计算 关系 编辑:程序博客网 时间:2024/05/20 04:11


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

Time Limit: 1000MS Memory Limit: 65536KB
SubmitStatistic

Problem Description

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

Input

 多组输入,到文件结尾。

每一组第一行有两个数nm表示n个点,m条有向边。接下来有m行,每行两个数uv代表uv有一条有向边。第m+2行有一个数q代表询问次数,接下来q行每行有一个询问,输入两个数为ab

注意:点的编号为0~n-12<=n<=5000000<=m<=5000000<=q<=500000a!=b,输入保证没有自环和重边

Output

 对于每一条询问,输出一行。若ab可以直接连通输出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;
}


0 0
原创粉丝点击