Codeforces
CF Step
Youtube Linkedin Discord Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

Code : Alternating Path

// User : silent_wood
// Submission : https://codeforces.com/contest/2204/submission/366956223
#include <bits/stdc++.h>

int main() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    std::cout.tie(nullptr);
    int T;
    std::cin >> T;
    while (T--) {
        int n, m;
        std::cin >> n >> m;
        std::vector<std::vector<int>> G(n);
        for (int i = 0; i < m; i++) {
            int u, v;
            std::cin >> u >> v;
            u--;
            v--;
            G[u].push_back(v);
            G[v].push_back(u);
        }
        int ans = 0;
        std::vector<int> vis(n), col(n);
        for (int u = 0; u < n; u++) {
            if (vis[u])
                continue;
            int cnt[2] = {};
            bool flag = false;
            auto dfs = [&](auto &&self, int u, int c) -> void {
                if (vis[u]) {
                    if (col[u] != c) {
                        flag = true;
                    }
                    return;
                }
                vis[u] = 1;
                col[u] = c;
                cnt[c]++;
                for (int v : G[u]) {
                    self(self, v, !c);
                }
            };
            dfs(dfs, u, 0);
            if (!flag)
                ans += std::max(cnt[0], cnt[1]);
        }
        std::cout << ans << std::endl;
    }
    return 0;
}