图的基本存储的基本方式二
Time Limit: 1000MS
Memory Limit: 65536KB
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
lin
#include <stdio.h>
#include <stdlib.h>
typedef struct node //数据太大,不能用二维数组
{
int data;
struct node *next;
}node;
int main()
{
int n,m,u,v;
int i;
int a,b,q;
node *head[500000],*p,*tail,*temp;
while(~scanf("%d %d",&n,&m)){
for(i=0; i<n; i++)//初始化节点
head[i] = NULL;
while(m--){
scanf("%d %d",&u,&v);
if(head[u]==NULL){ //第一次连,直接连
head[u] = (node *)malloc(sizeof(struct node));
head[u]->data = v;
head[u]->next = NULL;//指向空
}
else{
temp = head[u]->next;//已经连通,插入,
p = (node *)malloc(sizeof(struct node));
p->data = v;
p->next = temp;
head[u]->next = p;
}
}
scanf("%d",&q);
while(q--){
int f = 0;
scanf("%d %d",&a,&b);
if(head[a]==NULL)
printf("No\n");
else{
temp = head[a];
while(temp){ //只要在次节点后面,表示都与他直接连通
if(temp->data==b){
f = 1;
break;
}
temp = temp->next;
}
if(f)
printf("Yes\n");
else
printf("No\n");
}
}
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
typedef struct node //数据太大,不能用二维数组
{
int data;
struct node *next;
}node;
int main()
{
int n,m,u,v;
int i;
int a,b,q;
node *head[500000],*p,*tail,*temp;
while(~scanf("%d %d",&n,&m)){
for(i=0; i<n; i++)//初始化节点
head[i] = NULL;
while(m--){
scanf("%d %d",&u,&v);
if(head[u]==NULL){ //第一次连,直接连
head[u] = (node *)malloc(sizeof(struct node));
head[u]->data = v;
head[u]->next = NULL;//指向空
}
else{
temp = head[u]->next;//已经连通,插入,
p = (node *)malloc(sizeof(struct node));
p->data = v;
p->next = temp;
head[u]->next = p;
}
}
scanf("%d",&q);
while(q--){
int f = 0;
scanf("%d %d",&a,&b);
if(head[a]==NULL)
printf("No\n");
else{
temp = head[a];
while(temp){ //只要在次节点后面,表示都与他直接连通
if(temp->data==b){
f = 1;
break;
}
temp = temp->next;
}
if(f)
printf("Yes\n");
else
printf("No\n");
}
}
}
return 0;
}