731C - Socks - CodeForces Solution


dfs and similar dsu graphs greedy *1600

Please click on ads to support us..

C++ Code:

#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define ull unsigned long long
#define all(x) x.begin(), x.end()
const int mod = 1e9+7;
const int maxn = 2e5+5;

vector<int> graph[maxn];
int col[maxn], visited[maxn];

int cnt;
map<int, int> freq;

void dfs(int u){
    visited[u] = 1;
    freq[col[u]] = freq[col[u]]+1;
    cnt++;
    for(int x : graph[u]){
        if(visited[x] == 0){
            dfs(x);
        }
    }
}


int main(){
    ios_base::sync_with_stdio(false); cin.tie(0);
    int n, m, k;
    cin >> n >> m >> k;
    for(int i = 0; i < n; i++) cin >> col[i];
    for(int i = 0; i < m; i++){
        int a, b;
        cin >> a >> b;
        a--; b--;
        graph[a].push_back(b);
        graph[b].push_back(a);
    }

    int sol = 0;
    for(int i = 0; i < n; i++){
        if(visited[i] == 0){
            freq.clear();
            cnt = 0;
            dfs(i);
            sol += cnt - max_element(freq.begin(), freq.end(), [](auto x, auto y){ return x.second < y.second; })->second;;
        }
    }

    cout << sol;

    return 0;
}


Comments

Submit
0 Comments
More Questions

1726C - Jatayu's Balanced Bracket Sequence
1726A - Mainak and Array
1613C - Poisoned Dagger
475B - Strongly Connected City
652B - z-sort
124B - Permutations
1496C - Diamond Miner
680B - Bear and Finding Criminals
1036E - Covered Points
1015D - Walking Between Houses
155B - Combination
1531A - Зингер | color
1678A - Tokitsukaze and All Zero Sequence
896A - Nephren gives a riddle
761A - Dasha and Stairs
1728B - Best Permutation
1728A - Colored Balls Revisited
276B - Little Girl and Game
1181A - Chunga-Changa
1728C - Digital Logarithm
1728D - Letter Picking
792B - Counting-out Rhyme
1195A - Drinks Choosing
5D - Follow Traffic Rules
1272A - Three Friends
1632D - New Year Concert
1400D - Zigzags
716C - Plus and Square Root
412A - Poster
844B - Rectangles