thảo luận Leetcode mỗi ngày

  • Người tạo chủ đề Người tạo chủ đề _Gia_Cat_Luong_
  • Ngày bắt đầu Ngày bắt đầu
Trạng thái
Không mở để trả lời thêm.
Điều kiện if(visitedAt[x][y] < cost) là để tránh trường hợp process lại 1 node mà mình đã dequeue trước đó với cost nhỏ hơn đúng không bác? Code trong editorial thì không thấy check case này. E thử return -1 nếu condition này xảy ra thì thấy nó vẫn pass hết test case. E có nhờ chatgpt gen ra test case để trigger condition đó nhưng cũng không ra :v Em nghĩ case này có thể không bao giờ xảy ra với đồ thị chỉ có 0 và 1.
Bác kia giải thích đúng rồi đấy bác, Dijkstra phải kẹp thêm điều kiện đó ko nhiều bài sẽ bị TLE đấy.
Mà mình code quen tay thì dùng luôn thôi chứ ko quan tâm là đồ thị chỉ có 0 1 hoặc là weighted graph

via theNEXTvoz for iPhone
 
Sửa lần cuối:
Bác kia giải thích đúng rồi đấy bác, Dijkstra phải kẹp thêm điều kiện đó ko nhiều bài sẽ bị TLE đấy.
Mà mình code quen tay thì dùng luôn thôi chứ ko quan tâm là đồ thị chỉ có 0 1 hoặc là weighted graph

via theNEXTvoz for iPhone
cái TH mà nhỏ hơn khi đồ thị trọng số không âm thôi, còn giá trị đồ thị trong bài chỉ 0 và 1 nên ko bị ảnh hưởng, apply thoải mái
 
bài hôm nay tuy hard nhưng đề lộ quá, chạy tay cũng dễ thấy. mai thêm ớt tí đi dạo này thèm ăn cay
mR7E4f6.png
 
Java:
class Solution {
    fun minimumObstacles(grid: Array<IntArray>): Int {
        val directions = arrayOf(-1 to 0, 0 to 1, 1 to 0, 0 to -1)
        val visit = mutableSetOf<Pair<Int, Int>>()
        val queue = PriorityQueue<Triple<Int, Int, Int>>(compareBy { it.third })
        queue.offer(Triple(0, 0, 0))
        while (queue.isNotEmpty()) {
            val (x, y, cnt) = queue.poll()
            if (visit.contains(x to y)) continue
            visit.add(x to y)
            for ((dx, dy) in directions) {
                val nx = x + dx
                val ny = y + dy
                if (nx == grid.lastIndex && ny == grid[0].lastIndex) return cnt

                if (nx in 0..grid.lastIndex
                    && ny in 0..grid[0].lastIndex
                    && !visit.contains(nx to ny)) {
                    val ncnt = if (grid[nx][ny] == 1) cnt + 1 else cnt
                    queue.offer(Triple(nx, ny, ncnt))
                }
            }
        }
        return -1
    }
}
 
cơm thêm Q3 Sep 29: https://leetcode.com/problems/count-of-substrings-containing-every-vowel-and-k-consonants-ii/

2 tiếng ngồi debug với IDE :too_sad:
1732812950889.png

Python:
class Solution:
    def countOfSubstrings(self, word: str, k: int) -> int:
        d, start, res, dp = defaultdict(int), 0, 0, [0] * (len(word) + 1)
        for i in range(len(word) - 1, -1, -1):
            if word[i] in 'aeiou': dp[i] = 1 + dp[i + 1]
        
        for i in range(len(word)):
            d[word[i]] += 1
            
            while all(d[v] >= 1 for v in 'aeiou') and (cons := (i - start + 1) - sum(d[v] for v in 'aeiou')) >= k:
                if cons == k:
                    res += (1 + dp[i+1])
                d[word[start]] -= 1
                start += 1
        return res
 
Sửa lần cuối:
cơm thêm: https://leetcode.com/problems/count-of-substrings-containing-every-vowel-and-k-consonants-ii/

2 tiếng ngồi debug với IDE :too_sad:
Python:
class Solution:
    def countOfSubstrings(self, word: str, k: int) -> int:
        d = defaultdict(int)
        start = 0
        res = 0
        dp = [0] * (len(word) + 1)
        for i in range(len(word) - 1, -1, -1):
            if word[i] in ('a', 'e', 'i', 'o', 'u'):
                dp[i] = 1 + dp[i + 1]
     
        for i in range(len(word)):
            d[word[i]] += 1
         
            while d['a'] >= 1 and d['e'] >= 1 and d['i'] >= 1 and d['o'] >= 1 and d['u'] >= 1 and ((i - start + 1) - (d['a'] + d['e'] + d['i'] + d['o'] + d['u'])) >= k:
                if (i - start + 1) - (d['a'] + d['e'] + d['i'] + d['o'] + d['u']) == k:
                    res += (1 + dp[i+1])
                
                d[word[start]] -= 1
                start += 1
        return res
bài này e làm lâu r, muộn r lười làm lại quá thôi đăng sol của e bác đọc cho vui
Java:
class Solution {
    public long countOfSubstrings(String word, int k) {
        int n = word.length();
        Map<Character, Integer> vowels = new HashMap();
        vowels.put('a',0);
        vowels.put('e',1);
        vowels.put('i',2);
        vowels.put('o',3);
        vowels.put('u',4);
        int[] freq=new int[5];
        Set<Character> set = new HashSet();
        int cntConsonant=0;
        long res=0;
        int l =0;
        int[] next = new int[n];
        int last =n;
        for(int i =n-1 ; i >=0;i--){
            char c = word.charAt(i);
            next[i]=last;
            if(!isVowel(c)) {
                last = i;
            }
        }
        for(int r =0;r<n;r++ ){
            char c = word.charAt(r);
            if(!isVowel(c)) cntConsonant++;
            else{
                freq[vowels.get(c)]++;
                set.add(c);
            }
             while (l < r && cntConsonant > k) {
                char cc = word.charAt(l);
                if (isVowel(cc)) {
                    if (--freq[vowels.get(word.charAt(l))] == 0) set.remove(word.charAt(l));
                } else {
                    cntConsonant--;
                }
                l++;
            }
            while (l < r && set.size()== 5 && cntConsonant == k) {
                res += (next[r] - r);
                char cc = word.charAt(l);
                if (isVowel(cc)) {
                    if (--freq[vowels.get(word.charAt(l))] == 0) set.remove(word.charAt(l));
                } else {
                    cntConsonant--;
                }
                l++;
            }
        }
        return res;
    }

    boolean isVowel(char c) {
        return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
    }
}
 
cơm thêm Q3 Sep 29: https://leetcode.com/problems/count-of-substrings-containing-every-vowel-and-k-consonants-ii/

2 tiếng ngồi debug với IDE :too_sad:
Xem tệp đính kèm 2805650
Python:
class Solution:
    def countOfSubstrings(self, word: str, k: int) -> int:
        d, start, res, dp = defaultdict(int), 0, 0, [0] * (len(word) + 1)
        for i in range(len(word) - 1, -1, -1):
            if word[i] in 'aeiou': dp[i] = 1 + dp[i + 1]
        
        for i in range(len(word)):
            d[word[i]] += 1
            
            while all(d[v] >= 1 for v in 'aeiou') and (cons := (i - start + 1) - sum(d[v] for v in 'aeiou')) >= k:
                if cons == k:
                    res += (1 + dp[i+1])
                d[word[start]] -= 1
                start += 1
        return res
Bài này xưa làm tí là ăn do nhìn ra sliding windows + tí trick.
Khi cái windows nó good và gặp đủ consonants thì việc gặp thêm 1 consonant nữa sẽ làm cái windows invalid. Nên ở mỗi index của consonent chỉ cần biết index consonant tiếp theo là đủ để tìm valid sub arrays
Hoặc là dùng trick atleast(k) - atleast(k+1)

via theNEXTvoz for iPhone
 
bài này e làm lâu r, muộn r lười làm lại quá thôi đăng sol của e bác đọc cho vui
Java:
class Solution {
    public long countOfSubstrings(String word, int k) {
        int n = word.length();
        Map<Character, Integer> vowels = new HashMap();
        vowels.put('a',0);
        vowels.put('e',1);
        vowels.put('i',2);
        vowels.put('o',3);
        vowels.put('u',4);
        int[] freq=new int[5];
        Set<Character> set = new HashSet();
        int cntConsonant=0;
        long res=0;
        int l =0;
        int[] next = new int[n];
        int last =n;
        for(int i =n-1 ; i >=0;i--){
            char c = word.charAt(i);
            next[i]=last;
            if(!isVowel(c)) {
                last = i;
            }
        }
        for(int r =0;r<n;r++ ){
            char c = word.charAt(r);
            if(!isVowel(c)) cntConsonant++;
            else{
                freq[vowels.get(c)]++;
                set.add(c);
            }
             while (l < r && cntConsonant > k) {
                char cc = word.charAt(l);
                if (isVowel(cc)) {
                    if (--freq[vowels.get(word.charAt(l))] == 0) set.remove(word.charAt(l));
                } else {
                    cntConsonant--;
                }
                l++;
            }
            while (l < r && set.size()== 5 && cntConsonant == k) {
                res += (next[r] - r);
                char cc = word.charAt(l);
                if (isVowel(cc)) {
                    if (--freq[vowels.get(word.charAt(l))] == 0) set.remove(word.charAt(l));
                } else {
                    cntConsonant--;
                }
                l++;
            }
        }
        return res;
    }

    boolean isVowel(char c) {
        return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
    }
}
Code mai fen viết khó đọc quá, nên học lại template về cửa sổ trượt để viết cho khỏi bug. Viết kiểu này gặp câu khác bug sml cho xem

via theNEXTvoz for iPhone
 
Python:
class Solution:
    def minimumTime(self, grid: List[List[int]]) -> int:

        if grid[0][1] > 1 and grid[1][0] > 1:
            return -1

        dirs = [(0, -1), (-1, 0), (0, 1), (1, 0)]
        pq = [(0, 0, 0)]
        m, n, visisted = len(grid), len(grid[0]), set((0, 0))

        while pq:
            time, u, v = heapq.heappop(pq)

            if u == m - 1 and v == n - 1:
                return time
            
            for dir in dirs:
                u1, v1 = u + dir[0], v + dir[1]
                if u1 >= m or u1 < 0 or v1 >= n or v1 < 0 or (u1, v1) in visisted:
                    continue
                visisted.add((u1, v1))
                heapq.heappush(pq, (max(time + 1, grid[u1][v1] + (1 - (grid[u1][v1] - time) & 1) ), u1, v1))

        return -1
 
JavaScript:
/**
 * @param {number[][]} grid
 * @return {number}
 */
var minimumTime = function (grid) {
    if (grid[0][1] > 1 && grid[1][0] > 1) {
        return -1;
    }
    const m = grid.length, n = grid[0].length;
    const q = new MinPriorityQueue();
    const nextOf = (i, j) => {
        return [[0, 1], [0, -1], [1, 0], [-1, 0]]
            .map(([ii, jj]) => [i + ii, j + jj])
            .filter(([ii, jj]) => ii >= 0 && ii < m && jj >= 0 && jj < n);
    };
    q.enqueue([0, 0], 0);
    grid[0][0] = -1;
    while (!q.isEmpty()) {
        const { element: [i, j], priority: p } = q.dequeue();
        if (i === m - 1 && j === n - 1) {
            return p;
        }
        for (const [ii, jj] of nextOf(i, j)) {
            if (grid[ii][jj] >= 0) {
                const k = Math.max(
                    p + 1,
                    grid[ii][jj] + ((grid[ii][jj] & 1) ^ ((ii + jj) & 1))
                );
                grid[ii][jj] = -1;
                q.enqueue([ii, jj], k);
            }
        }
    }
};
 
Má nó assign cái biến neighborCost ở bên ngoài loop ngồi debug cả tiếng mới thấy cay thế nhỉ =((
Python:
class Solution:
    def minimumTime(self, grid: List[List[int]]) -> int:
        if grid[0][1] > 1 and grid[1][0] > 1:
            return -1
        m, n = len(grid), len(grid[0])
        visited = set()
        visited.add((0, 0))
        heap = []
        heapq.heappush(heap, (0, 0, 0))
        directions = [[-1, 0], [1, 0], [0, -1], [0, 1]]
        while heap:
            cost, r, c = heapq.heappop(heap)
            if r == m - 1 and c == n - 1:
                return cost
            for dx, dy in directions:
                nx = dx + r
                ny = dy + c
                neighborCost = cost + 1
                if nx < 0 or nx >= m or ny < 0 or ny >= n or (nx, ny) in visited:
                    continue
                if neighborCost < grid[nx][ny]:
                    diff = grid[nx][ny] - neighborCost
                    neighborCost = grid[nx][ny] + diff%2
                visited.add((nx, ny))
                heapq.heappush(heap, (neighborCost, nx, ny))   
        return -1
 
Sửa lần cuối:
Má nó assign cái biến neighborCost ở bên ngoài loop ngồi debug cả tiếng mới thấy cay thế nhỉ =((
Python:
class Solution:
    def minimumTime(self, grid: List[List[int]]) -> int:
        if grid[0][1] > 1 and grid[1][0] > 1:
            return -1
        m, n = len(grid), len(grid[0])
        visited = set()
        visited.add((0, 0))
        heap = []
        heapq.heappush(heap, (0, 0, 0))
        directions = [[-1, 0], [1, 0], [0, -1], [0, 1]]
        while heap:
            cost, r, c = heapq.heappop(heap)
            if r == m - 1 and c == n - 1:
                return cost
            for dx, dy in directions:
                nx = dx + r
                ny = dy + c
                neighborCost = cost + 1
                if nx < 0 or nx >= m or ny < 0 or ny >= n or (nx, ny) in visited:
                    continue
                if neighborCost < grid[nx][ny]:
                    diff = grid[nx][ny] - neighborCost
                    neighborCost = grid[nx][ny] + diff%2
                visited.add((nx, ny))
                heapq.heappush(heap, (neighborCost, nx, ny))  
        return -1
sểm hia =((
 
Leetcode cho bài hard ăn mừng thanksgiving à :hungry:
Python:
class Solution:
    def minimumTime(self, grid: List[List[int]]) -> int:
        INF = 10**9
        vectors = [
            (-1, 0), (0, 1), (1, 0), (0, -1)
        ]


        m = len(grid)
        n = len(grid[0])

        next_moves = 0
        for (x, y) in vectors:
            if x < 0 or x >= m or y < 0 or y >= n:
                continue
            
            if grid[x][y] <= 1:
                next_moves += 1
        if next_moves == 0:
            return -1

        d = [[INF] * n for _ in range(m)]
        d[0][0] = 0
        h = [(0, (0, 0))]

        while h:
            c, (u, v) = heappop(h)
            if c != d[u][v]:
                continue
            
            if u == m-1 and v == n-1:
                return c

            for (vx, vy) in vectors:
                x, y = u + vx, v + vy

                if x < 0 or x >= m or y < 0 or y >= n:
                    continue
                
                if d[u][v] + 1 >= grid[x][y]:
                    cost = d[u][v] + 1
                elif d[u][v] & 1:
                    cost = grid[x][y]
                    if cost & 1:
                        cost += 1
                else:
                    cost = grid[x][y]
                    if not cost & 1:
                        cost += 1
                
                
                if cost < d[x][y]:
                    d[x][y] = cost
                    heappush(h, (cost, (x, y)))
        return d[m-1][n-1]
 
Trạng thái
Không mở để trả lời thêm.

Thống kê chủ đề

Ngày tạo
_Gia_Cat_Luong_,
Người trả lời cuối
Vipluckystar,
Trả lời
17.755
Lượt xem
1.215.908
Quay lại
Lên đầu trang