题目:https://acm.sdut.edu.cn/onlinejudge3/problems/3117
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <stdlib.h>
#include <memory.h>
#include <limits.h>
#include <vector>
using namespace std;
struct node // 邻链表实现
{
int v;
node *next;
} * arr[500005], *p;
void add(int a, int b)
{
p = new node;
if (arr[a] == NULL)
{
p->v = b;
p->next = NULL;
arr[a] = p;
}
else
{
p->v = b;
p->next = arr[a]->next;
arr[a]->next = p;
}
}
bool query(int l, int r)
{
node *a = arr[l];
while (a)
{
if (a->v == r)
{
return true;
}
a = a->next;
}
return false;
}
//
struct node //链式前向星
{
int data;
int next;
} edge[500005];
int cnt;
int head[500005];
void add(int u, int v)
{
edge[cnt].data = v;
edge[cnt].next = head[u];
head[u] = cnt++;
}
bool query(int u, int v)
{
for (int i = head[u]; i != -1; i = edge[i].next)
{
if (edge[i].data == v)
return true;
}
return false;
}
int main()
{
ios ::sync_with_stdio(false);
int n, m;
while (cin >> n >> m)
{
memset(arr, 0, sizeof(arr));
while (m--)
{
int a, b;
cin >> a >> b;
add(a, b);
}
int q;
cin >> q;
while (q--)
{
int a, b;
cin >> a >> b;
if (query(a, b))
{
cout << "Yes\n";
}
else
{
cout << "No\n";
}
}
vector<int> pict[500005];
int u, v;
while (m--)
{
cin >> u >> v;
pict[u].push_back(v);
}
int q;
cin >> q;
while (q--)
{
int a, b;
cin >> a >> b;
int flag = 0;
int mm = pict[a].size();
for (int i = 0; i < mm; i++)
{
if (b == pict[a][i])
{
flag = 1;
break;
}
}
if (flag)
cout << "Yes\n";
else
cout << "No\n";
}
}
int n, m, u, v, q; // 链式前向星,用head数组来储存每边的第一个
while (cin >> n >> m)
{
cnt = 0;
memset(head, -1, sizeof(head));
while (m--)
{
cin >> u >> v;
add(u, v);
}
cin >> q;
while (q--)
{
cin >> u >> v;
if (query(u, v))
{
cout << "Yes\n";
}
else
{
cout << "No\n";
}
}
}
return 0;
}
引用博客:https://blog.csdn.net/rwbyblake/article/details/106281836