SDUT-OJ 3117图的基本存储的基本方式二

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

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。

Sample

Input 

2 1
0 1
2
0 1
1 0

Output 

Yes
No

Hint

邻接表 

#include<bits/stdc++.h>
using namespace std;
const int N=500100;//最大定点数;
struct vnode
{
    int vex;//顶点域,存储定点信息;
    struct arcnode *firstarc;//边表头指针
};
struct arcnode
{
    int adj;//存储它的邻接点;
    int weight;//边的权值
    struct arcnode *next;//链域,指向下一个邻接点;
};
vnode head[N];//顶点数组;
int n,m;//点的数量,边的数量

int main()
{
    while(~scanf("%d %d",&n,&m))
    {

        for(int i=1; i<=n; i++)
        {
            head[i].vex=i;
            head[i].firstarc=NULL;//初始化;
        }
        int u,v,w;
        for(int i=1; i<=m; i++)
        {
            scanf("%d %d",&u,&v);
            arcnode *p=new arcnode;
            p->adj=v;//存储邻接点
            p->next=head[u].firstarc;//连接表头;
            head[u].firstarc=p;
        }
        int t;
        scanf("%d",&t);
        while(t--)
        {
            int a,b;
            int flag=0;
            scanf("%d %d",&a,&b);
            arcnode *tmp=head[a].firstarc;
            for(; tmp; tmp=tmp->next)
            {
                if(tmp->adj==b)
                {
                    flag=1;
                    break;
                }
            }
            if(flag==1)
            {
                printf("Yes\n");
            }
            else
            {
                printf("No\n");
            }
        }
    }
    return 0;
}

链式前向星

#include <bits/stdc++.h>
#define N 500010
using namespace std;
struct edge
{
    int to,w,next;
};
int n,m,cnt;
edge e[N];
int head[N];
void addedge(int u,int v)
{
    cnt++;
    e[cnt].to=v;
    e[cnt].next=head[u];
    head[u]=cnt;
}
int main()
{
    while(cin>>n>>m)
    {

        int u,v,w;
        memset(head,-1,sizeof(head));
        for(int i=1; i<=m; ++i)
        {
            cin>>u>>v;
            addedge(u,v);
        }
        int t;
        scanf("%d",&t);
        while(t--)
        {
            int a,b;
            int flag=0;
            scanf("%d %d",&a,&b);
            for(int j=head[a];j!=-1;j=e[j].next)
            {
                if(e[j].to==b)
                {
                    flag=1;
                    break;
                }
            }
            if(flag==1)
            {
                printf("Yes\n");
            }
            else
            {
                printf("No\n");
            }
        }
    }
    return 0;
}

 

 

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值