Блог пользователя am1rkng

Автор am1rkng, история, 5 недель назад, По-русски

Hook!!!

Hello everyone!

If you are struggling with graph problems, this post will save you a LOT of time. Today I will explain one of the most powerful techniques — DFS (Depth-First Search)

What is DFS? DFS is a technique where we go as deep as possible in a graph before backtracking.

In simple words: Go forward → go deeper → if stuck → go back

Where is it used? DFS is used in:

1) Connected components 2) Cycle detection 3) Tree traversal 4) Grid problems (VERY COMMON)

Pattern If you see:

  • "graph"
  • "visit all nodes"
  • "connected"
  • "grid"

Think about DFS immediately

Code (C++) **#include <bits/stdc++.h> using namespace std;

const int N = 200005;

vector g[N]; bool vis[N];

void dfs(int v) { vis[v] = true;

for (int to : g[v]) {
    if (!vis[to]) {
        dfs(to);
    }
}

}

int main() { int n, m; cin >> n >> m;

for (int i = 0; i < m; i++) {
    int u, v;
    cin >> u >> v;
    g[u].push_back(v);
    g[v].push_back(u);
}

int cnt = 0;

for (int i = 1; i <= n; i++) {
    if (!vis[i]) {
        dfs(i);
        cnt++;
    }
}

cout << cnt << "\n";

}**

Final Tip DFS is one of the easiest ways to gain rating on Codeforces.

Master it → solve 50+ problems → you will feel huge progress

Ending Thanks for reading!

If this post helped you: please upvote Good Bye!

Полный текст и комментарии »

  • Проголосовать: нравится
  • +24
  • Проголосовать: не нравится

Автор am1rkng, история, 7 недель назад, По-русски

Hello everyone!

Today I want to explain one of the most useful techniques in competitive programming — Two Pointers * What is Two Pointers?

Two pointers is a technique where we use two indices to iterate over an array or string.

Usually:

  • One pointer starts from the beginning
  • Another from the end (or also from beginning)
  • Example Problem

Given an array, find if there exist two numbers whose sum equals k.

  • Idea
  1. Sort the array

  2. Set:

    left = 0 right = n — 1

  3. While left < right:

    if a[left] + a[right] == k → FOUND if sum < k → left++ if sum > k → right--

  • Code (C++)
#include <bits/stdc++.h>
using namespace std;

int main() {
    int n, k;
    cin >> n >> k;
    vector<int> a(n);
    for(int i = 0; i < n; i++) cin >> a[i];
    sort(a.begin(), a.end());
    int l = 0, r = n &mdash; 1;
    while(l < r) {
        int sum = a[l] + a[r];
        if(sum == k) {
            cout << "YES\n";
            return 0;
        }
        else if(sum < k) l++;
        else r--;
    }
    cout << "NO\n";
}
  • Complexity

Sorting: O(n log n) Two pointers: O(n)

Total: O(n log n)

  • When to Use?

1) Sorted arrays 2)Pair problems 3)Subarray problems

*Final Tip

If you see:

1) “find pair” 2) “sum equals k” 3) “continuous segment” Think about Two Pointers

Thanks for reading! If this helped you, please upvote

Полный текст и комментарии »

  • Проголосовать: нравится
  • +21
  • Проголосовать: не нравится