1419. Minimum Number of Frogs Croaking

该编程解决方案通过构建哈希表,分析给定的Frogs序列(如croak),确保字符遵循特定规律(有k必有a,有a必有o),并处理异常情况,计算最少的青蛙叫声次数。
  • 找规律
  • 从后向前思考,有 k 时必须有 a,有 a 时前面必须有 o,并且一一对应
  • 由此构建哈希表,比如出现 k,则出现 a 的次数减一,k 则加一
  • 处理 c 的起始情况
  • 异常情况的判断:若出现 roak中的一个,前面没有与之对应的前一个字符,则返回-1;
  • 最后返回值为 k 的个数,前提是此时哈希表中其他字符计数为0
class Solution {
public:
    int minNumberOfFrogs(string croakOfFrogs) {
        string s = "croak";
        unordered_map<char, int> index; // 每个字符与下标映射
        for(int i = 0; i < s.size(); i++)
            index[s[i]] = i;
        vector<int> hash(s.size());
        for(int i = 0; i < croakOfFrogs.size(); i++)
        {
            if(croakOfFrogs[i] == s[0])
            {
                if(hash[s.size() - 1] != 0)
                    hash[s.size() - 1]--;
                hash[0]++;
            }
            else
            {
                if(hash[index[croakOfFrogs[i]] - 1] == 0)
                    return -1;
                hash[index[croakOfFrogs[i]] - 1]--;
                hash[index[croakOfFrogs[i]]]++;

            }
        }
        for(int i = 0; i < s.size() - 1; i++)
        {
            if(hash[i] != 0)
                return -1;
        }
        return hash[s.size() - 1];
    }
};
时间限制:1000ms 内存限制:512MB 输入文件名:s.in 输出文件名:s.out 题目描述: 给定一个长度为 N 的只含小写字母的字符串 S,每次操作可以选择一个位置 1 ≤ x ≤ N 和一个小写字母 c,接着把 Sₓ 改为 c。 你需要操作若干次,使得操作结束后,每相邻 K 个字符都不同,求最少的操作次数。保证 1 ≤ K ≤ 13。 输入格式: 第一行一个整数 T,表示测试数据组数。 接下来 T 组测试数据,对于每组测试数据: 第一行两个整数 N, K,分别表示字符串长度和子串的长度。 第二行一个长度为 N 的字符串 S。 输出格式: 对于每组测试数据,输出一行一个整数表示最少的操作次数。 样例输入 1(input1): 5 6 3 abaaba 5 2 hooch 8 3 cherykid 9 3 abbabbaba 9 3 aabbaabba 样例输出 1(output1): 2 1 0 3 4 样例 #1 解释: 对于第一组数据,可以用 2 次操作把 S 改为 abcabc,每相邻三个字符组成的字符串分别是 abc、bca、cab、abc,都满足包含的字符互不相同。 对于第三组数据,请注意可以不进行操作。 数据范围: 对于所有数据,保证 1 ≤ T ≤ 10⁵,1 ≤ ∑N ≤ 10⁶,1 ≤ K ≤ 13,S 中只含有小写字符。 子任务说明: 子任务 1:∑N ≤ 10,K ≤ 10,分值 10 子任务 2:∑N ≤ 100,K ≤ 10,分值 10 子任务 3:∑N ≤ 10³,K ≤ 13,分值 10 子任务 4:∑N ≤ 10⁵,K ≤ 3,分值 20 子任务 5:∑N ≤ 10⁵,K ≤ 13,分值 20 子任务 6:∑N ≤ 10⁶,K ≤ 13,分值 30 用C++ 14 With O2的语言写一段代码,不要超时,不要注释,用万能头,变量名用一个字母表示,最终代码写好后随便写5组边缘样例测试一下刚刚写的代码(把代码放进编译器输出检查),然后根据刚刚的代码测试修改代码,将这两段代码里的变量名用一个字母替代。代码加上空格,使代码有可读性(实在拿不到全分,也可以拿部分分,尽量多拿!)注意加上文件读写!!!!!!!!!!
07-12
A player wants to press the direction buttons as little as possible so that both frogs arrive at the destination to finish the game. Find the minimum number of times the player pressed the buttons to finish the game. If the frog or green frog cannot arrive at the destination, output -1. [Figure] For example, let's look at the case where a grid with six rows and six columns is given. The frog is located at (6, 1), the green frog is located at (1, 6), and the destination is (2, 3) as shown in the [Figure]. Walls are marked with #. First, the frog arrives at the destination first by moving eight times as shown on the left side of the [Figure], and the green frog moves to the opposite direction at the same time and is located at (6, 4). Next, as shown on the right side of the [Figure], when the green frog arrives at the destination by moving it five times, you pressed the buttons 13 times for both frogs to arrive at the destination. This is the minimum number of times you press the buttons. [Constraints] 1. N and M are integers from 2 to 40. 2. R1, R2, and R3 are integers from 1 to N. 3. C1, C2, and R3 are integers from 1 to M. 4. Both frogs cannot be at the same location while they are moving. 5. Walls are not the start and destination of both frogs, and the start positions of the two frogs are not their destinations. [Input] First, the number T of test cases is given, followed by T test cases. On the first line of each test case, N and M are given, separated by spaces. On the next line, R1, C1, R2, C2, R3, and C3 are given in the order, separated by spaces. Over the next N lines, a string of length M is given..” represents a position in the grid to which both frogs can move, and “#” represents a wall. [Output] Output one line per test case. For each test case, output “#x” (where x is the number of the test case, starting from 1), leave a space, and then output the answer of the relevant test case. [Example of Input and Output] (Input) 1 6 6 6 1 1 6 2 3 ....#. .#..#. .#..#. .#..#. .#.##. .#....
09-16
To solve this problem, we can model it as a variation of the shortest path problem in a grid, where two frogs move simultaneously, and the player wants to minimize the total number of button presses (i.e., moves) such that both frogs reach the destination. ### Approach: 1. **Model the problem as a BFS (Breadth-First Search):** - Each state in the BFS will represent the positions of both frogs and the total number of moves taken so far. - The state can be stored as a tuple: `(r1, c1, r2, c2, moves)` where `(r1, c1)` is the position of the first frog and `(r2, c2)` is the position of the second frog. - The goal is to reach the destination `(R3, C3)` for both frogs. 2. **Movement Rules:** - Frogs can move in four directions: up, down, left, right. - If a frog is already at the destination, it can stay there while the other frog continues to move. - Frogs cannot occupy the same position while moving. 3. **Handling Walls:** - Frogs cannot move into walls (`#`). 4. **BFS Algorithm:** - Use a queue to perform BFS. - Use a visited set to avoid revisiting the same state. - For each state, generate all possible next states by moving each frog in all valid directions. - Stop the BFS when both frogs reach the destination. 5. **Edge Cases:** - If either frog cannot reach the destination, return `-1`. ### Implementation in Python: ```python from collections import deque import sys input = sys.stdin.read def bfs(grid, N, M, start1, start2, destination): directions = [(-1, 0), (1, 0), (0, -1), (0, 1)] # up, down, left, right visited = set() queue = deque() # Initial state: (r1, c1, r2, c2, moves) queue.append((start1[0], start1[1], start2[0], start2[1], 0)) visited.add((start1[0], start1[1], start2[0], start2[1])) while queue: r1, c1, r2, c2, moves = queue.popleft() # Check if both frogs have reached the destination if (r1, c1) == destination and (r2, c2) == destination: return moves # Generate all possible next states for dr, dc in directions: nr1, nc1 = r1 + dr, c1 + dc nr2, nc2 = r2 + dr, c2 + dc # Check if the new positions are valid for frog 1 if 0 <= nr1 < N and 0 <= nc1 < M and grid[nr1][nc1] != '#': pos1 = (nr1, nc1) else: pos1 = (r1, c1) # Frog stays in place if move is invalid # Check if the new positions are valid for frog 2 if 0 <= nr2 < N and 0 <= nc2 < M and grid[nr2][nc2] != '#': pos2 = (nr2, nc2) else: pos2 = (r2, c2) # Frog stays in place if move is invalid # Check if frogs are at the same position (not allowed) if pos1 == pos2 and pos1 != destination: continue # Add the new state to the queue if not visited new_state = (pos1[0], pos1[1], pos2[0], pos2[1]) if new_state not in visited: visited.add(new_state) queue.append((pos1[0], pos1[1], pos2[0], pos2[1], moves + 1)) # If destination is unreachable return -1 # Main function to read input and process test cases def main(): data = input().splitlines() T = int(data[0]) idx = 1 for case in range(1, T + 1): N, M = map(int, data[idx].split()) idx += 1 R1, C1, R2, C2, R3, C3 = map(int, data[idx].split()) idx += 1 # Adjusting for 0-based indexing start1 = (R1 - 1, C1 - 1) start2 = (R2 - 1, C2 - 1) destination = (R3 - 1, C3 - 1) grid = [] for _ in range(N): grid.append(list(data[idx])) idx += 1 result = bfs(grid, N, M, start1, start2, destination) print(f"#{case} {result}") # Run the main function if __name__ == "__main__": main() ``` ### Explanation of the Code: - **BFS Function:** - The `bfs` function performs a breadth-first search to find the shortest number of moves required for both frogs to reach the destination. - It uses a queue to explore all possible states and a set to track visited states to avoid redundant checks. - **Main Function:** - The `main` function reads input, processes each test case, and prints the result for each one. ### Sample Output: For the given input: ``` 1 6 6 6 1 1 6 2 3 ....#. .#..#. .#..#. .#..#. .#.##. .#.... ``` The output would be: ``` #1 13 ``` This solution ensures that both frogs reach the destination in the minimum number of moves while avoiding walls and ensuring they do not collide.
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值