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

图的基本存储的基本方式二
Time Limit: 1000MS Memory Limit: 65536KB
Submit Statistic Discuss
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

#include <iostream>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
typedef struct node
{
    int data;
    node *next;
}node;
struct each
{
    node *head;
    node *rear;
}links[500000];;
void linksInit(each &link)
{
    link.head = (node *)malloc(sizeof(node));
    link.head->next = NULL;
    link.rear = link.head;
}

void linksPush(each &link,int data)
{
    node *p;
    p = (node *)malloc(sizeof(node));
    p->data = data;
    p->next = link.rear->next;
    link.rear->next = p;
    link.rear = p;
}

bool isof(each &link,int data)
{
    if(link.head==NULL)
    {
        return 0;
    }
    node *p;
    p = link.head->next;
    while(p)
    {
        if(p->data==data)
        {
            return 1;
        }
        p=p->next;
    }
    return 0;
}

void print(each &link)
{
    if(link.head==NULL)
        return;
    node *q = link.head->next;
    while(q)
    {
        printf("%d ",q->data);
        q = q->next;
    }
    cout<<endl;
}

int main()
{
    int n,m;
    while(~scanf("%d %d",&n,&m))
    {
        for(int i = 0;i<=500000;i++)
        {
            if(links[i].head!=NULL)
            {
                links[i].head->next = NULL;
                links[i].head = NULL;
            }
        }
        for(int i =0;i<m;i++)
        {
            int x,y;
            scanf("%d %d",&x,&y);
            if(links[x].head==NULL)
            {
                linksInit(links[x]);
                linksPush(links[x],y);
            }
            else
            {
                linksPush(links[x],y);
            }
        }
//        for(int i = 0;i<5;i++)
//        {
//            print(links[i]);
//        }
        //print(links[3]);
        int q;
        scanf("%d",&q);
        for(int i = 0;i<q;i++)
        {
            int x,y;
            scanf("%d %d",&x,&y);
            if(isof(links[x],y))
            {
                printf("Yes\n");
            }
            else
            {
                printf("No\n");
            }
        }

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值