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

图的基本存储的基本方式四
Time Limit: 2500 ms Memory Limit: 10000 KiB

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

Input
多组输入,到文件结尾。

每一组第一行有一个数n表示n个点。接下来给出一个n*n的矩阵 表示一个由邻接矩阵方式存的图。
矩阵a中的元素aij如果为0表示i不可直接到j,1表示可直接到达。
之后有一个正整数q,表示询问次数。
接下来q行每行有一个询问,输入两个数为a,b。

注意:点的编号为0~n-1,2<=n<=5000,0<=q<=100,0 <= a,b < n。
保证可达边的数量不超过1000

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

Sample Input
2
0 1
0 0
2
0 1
1 0
Sample Output
Yes
No
Hint
Source
LeiQ

此题用二维数组储存会超时,所以用链表储存节点。具体步骤和图的基本存储的基本方式二基本相同。

#include <stdio.h>
#include <stdlib.h>

struct node
{
    int date;
    struct node *next;
};
int main()
{
    struct node *head[5005],*p,*q;
    int n,i,j,x,t,a,b,flag;
    while(scanf("%d",&n)!=EOF)
    {
        for(i=0;i<n;i++)
            head[i]=NULL;
        for(i=0;i<n;i++)
            for(j=0;j<n;j++)
        {
            scanf("%d",&x);
            if(x)
            {
                p=(struct node*)malloc(sizeof(struct node));
                p->date=j;
                p->next=NULL;
                if(head[i]==NULL)
                {
                    head[i]=(struct node*)malloc(sizeof(struct node));
                    head[i]->next=p;
                }
                else
                {
                    q=head[i]->next;
                    head[i]->next=p;
                    p->next=q;
                }
            }
        }
        scanf("%d",&t);
        while(t--)
        {
            flag=0;
            scanf("%d%d",&a,&b);
            if(head[a]==NULL)
                printf("No\n");
            else
            {
                q=head[a];
                while(q)
                {
                    if(q->date==b)
                    {
                        flag=1;
                        break;
                    }
                    else
                        q=q->next;
                }
                if(flag)
                    printf("Yes\n");
                else
                    printf("No\n");
            }
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Dmenghu/article/details/81662915