版权声明:iQXQZX https://blog.csdn.net/Cherishlife_/article/details/85382306
图的基本存储的基本方式四 (邻接链表)
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
思路:
gra[i] = j; 矩阵上的元素(i, j) 放在邻接链表中 存在有向边 gra[i]->data = j; 不存在 gra[i] = NULL;
#include <bits/stdc++.h>
using namespace std;
struct node
{
int data; // 存点的j
node *next;
};
int main()
{
ios::sync_with_stdio(false);
node *p, *gra[5005];
int n, a, b, t;
while (cin >> n)
{
for (int i = 0; i < n; i++)
gra[i] = NULL;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
cin >> a;
if (a == 1)
{
if (gra[i] == NULL)
{
gra[i] = new node;
gra[i]->data = j;
gra[i]->next = NULL;
}
else
{
p = new node;
p->next = gra[i]->next;
p->data = j;
gra[i]->next = p;
}
}
}
}
cin >> t;
while (t--)
{
cin >> a >> b;
int flag = 0;
p = gra[a];
while (p)
{
if (p->data == b)
{
flag = 1;
break;
}
p = p->next;
}
if (flag)
cout << "Yes" << endl;
else
cout << "No" << endl;
// if (gra[a] == NULL)
// cout << "No" << endl;
// else
// {
// p = gra[a];
// while (p)
// {
// if (p->data == b)
// {
// flag = 1;
// break;
// }
// p = p->next;
// }
// if (flag == 1)
// cout << "Yes" << endl;
// else
// cout << "No" << endl;
// }
}
}
return 0;
}