用bfs求出每个连通分支的层数,然后把层数/2加起来为什么不对啊。。求助大佬。代码如下:
#include<iostream>
#include<queue>
using namespace std;
const int N = 10005;
bool g[N][N];
int color[N];
int main() {
int n, m, ans = 0;
cin >> n >> m;
for (int i = 1; i <= n; ++i)g[i][i] = 0;
for (int i = 1; i <= m; ++i) {
int a, b;
cin >> a >> b;
g[a][b] = g[b][a] = 1;
}
queue<int>q;
for (int i = 1; i <= n; ++i) {
if (color[i]) continue;
int cnt1 = 1, cnt2 = 0, res = 0;
q.push(i); color[i] = 1;
while (!q.empty()) {
int t = q.front();
q.pop();
for (int i = 1; i <= n; ++i) {
if (color[i] || g[t][i] == 0)continue;
q.push(i);
color[i] = 3 - color[t];
}
--cnt1, ++cnt2;
if (!cnt1)cnt1 = cnt2, cnt2 = 0, ++res;
}
ans += res/2;
}
for (int i = 1; i <= n; ++i)
for(int j=i+1;j<=n;++j)
if (g[i][j] && color[i] == color[j]) {
cout << "Impossible";
return 0;
}
cout << ans;
}