这道题大体上就是对一个图进行染色,相邻的两个点不能被染上相同的颜色,那么对于图中的点,如果该点没被染色,就把它染色,同时向外扩展。每次染色一定就染完了一个连通块,所以最后要么所有点被染色,要么无解。最后选取用的比较少的颜色为答案。
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;
const int maxn = 222;
vector<int> G[maxn];
int n, m, x, y, col[maxn];
bool dfs(int u, int &tot, int &cnt){
tot += 1;
if (col[u] == 1) cnt += 1;
for (int i = 0; i < G[u].size(); i++){
int v = G[u][i];
if (col[u] == col[v]) return 0;
if (!col[v]){
col[v] = 3 - col[u];
if (!dfs(v, tot, cnt)) return 0;
}
}
return 1;
}
int main(){
int cs;
scanf("%d", &cs);
while(cs--){
scanf("%d%d", &n, &m);
for (int i = 0; i <= n; i++) G[i].clear();
for (int i = 0; i < m; i++){
scanf("%d%d", &x, &y);
G[x].push_back(y);
G[y].push_back(x);
}
memset(col, 0, sizeof(col));
int ans = 0;
bool f = 1;
for (int i = 0; i < n; i++){
if (!col[i]){
col[i] = 1;
int cnt = 0, tot = 0;
if (!dfs(i, tot, cnt)){
f = 0;
break;
}
if (tot == 1) ans += 1;
else ans += min(cnt, tot - cnt);
}
}
if (f) printf("%d\n", ans);
else puts("-1");
}
return 0;
}