二分图的判定hihocoder1121 and hdu3478

时间:2023-12-19 21:14:38

这两个题目都是二分图的判定,用dfs染色比较容易写。

算法流程:

选取一个没有染色的点,然后将这个点染色,那么跟他相连的所有点一定是不同颜色的,所以,如果存在已经染过颜色的,如果和这个颜色相同的话,就说明不是二分图,否则,继续从这个点往下染。

hihocoder

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std; const int maxn = ;
vector<int> mp[maxn];
int color[maxn];
void init(int n)
{
memset(color, -, sizeof(color));
for (int i = ; i <= n; i++) mp[i].clear();
}
bool dfs(int u, int c)//用0和1分别表示两种颜色
{
color[u] = c;
for (int i = ; i < mp[u].size(); i++)
{
if (color[mp[u][i]] == c) return false;
if (color[mp[u][i]] == - && !dfs(mp[u][i], c ^ )) return false;
}
return true;
}
int main()
{
int T, n, m;
scanf("%d", &T);
while (T--)
{
int u, v;
scanf("%d%d", &n, &m);
init(n);
for (int i = ; i < m; i++)
{
scanf("%d%d", &u, &v);
mp[u].push_back(v);
mp[v].push_back(u);
}
bool ans = true;
for (int i = ; i <= n; i++)
{
if (color[i] == - && !dfs(i, ))
{
ans = false;
break;
}
}
printf("%s\n", ans ? "Correct" : "Wrong");
}
return ;
}

hdu3478

#include <cstdio>
#include <cstring>
#include <vector>
using namespace std; const int maxn = ;
vector<int> mp[maxn];
int color[maxn];
void init(int n)
{
memset(color, -, sizeof(color));
for (int i = ; i < n; i++) mp[i].clear();
}
bool dfs(int u, int c)
{
color[u] = c;
for (int i = ; i < mp[u].size(); i++)
{
if (color[mp[u][i]] == c) return false;
if (color[mp[u][i]] == - && !dfs(mp[u][i], c ^ )) return false;
}
return true;
}
int main()
{
int T, n, m, S, kase = ;
scanf("%d", &T);
while (T--)
{
scanf("%d%d%d", &n, &m, &S);
if (n == )
{
printf("Case %d: YES\n", ++kase);
continue;
}
init(n);
int u, v, cnt = ;
for (int i = ; i < m; i++)
{
scanf("%d%d", &u, &v);
mp[u].push_back(v);
mp[v].push_back(u);
}
bool flag = dfs(S, );
if (flag)
printf("Case %d: NO\n", ++kase);
else
printf("Case %d: YES\n", ++kase);
} return ;
}