随便选个点跑spfa。
跑完检查一下是不是存在dist[i]=false的点。如果有就不连通,否则就连通了。
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
const int N = 1010, M = 10010;
int n, m;
int h[N], e[M], ne[M], idx;
bool dist[N], st[N];
void add(int a, int b)
{
e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}
void spfa()
{
memset(dist, false, sizeof dist);
memset(st, false, sizeof st);
queue<int> q;
dist[1] = true;
q.push(1);
st[1] = true;
while (!q.empty())
{
auto t = q.front(); q.pop();
st[t] = false;
for (int i = h[t]; ~i; i = ne[i])
{
int j = e[i];
if (!dist[j])
{
dist[j] = true;
if (!st[j])
q.push(j), st[j] = true;
}
}
}
}
int main()
{
while (cin >> n >> m)
{
memset(h, -1, sizeof h);
idx = 0;
while (m--)
{
int a, b;
cin >> a >> b;
add(a, b), add(b, a);
}
spfa();
bool flag = true;
for (int i = 1; i <= n; ++i)
{
if (!dist[i])
{
flag = false;
break;
}
}
if (flag)
puts("YES");
else
puts("NO");
}
return 0;
}