version stringclasses 1
value | style stringclasses 2
values | subset stringclasses 12
values | question_id stringlengths 9 23 | question stringlengths 27 8.13k | solution stringlengths 99 5.97k | test stringlengths 105 4.45k | test_info listlengths 0 13 | gpt_pass_sequence listlengths 1 10 | gpt_pass_trial_num int64 1 10 | gpt_difficulty stringclasses 3
values | gpt_pass_percentage float64 0.1 1 | trials dict | chosen_trial stringclasses 10
values | metadata dict | benchmark_similarity float64 0.16 0.93 | benchmark_instruction stringclasses 1
value | benchmark_task_id stringclasses 1
value | filter_reason stringclasses 1
value | base_id stringlengths 7 21 | variant stringclasses 2
values | top_function_names listlengths 2 13 | n_top_functions int64 2 13 | helper_call_edges listlengths 1 16 | n_helper_call_edges int64 1 16 | harness_functions listlengths 0 3 | structural_wrapper bool 1
class | class_names listlengths 0 5 | has_class bool 2
classes | test_kind stringclasses 1
value | test_has_solution_import bool 2
classes | third_party_imports listlengths 0 5 | stdlib_only bool 2
classes | question_norm_sha1 stringlengths 40 40 | solution_ast_sha1 stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
v1.0 | complete | Codeforces | Codeforces_19630_C | def minMaxWorkload(m: int, n: int, dishes: List[int]) -> int:
""" Distribute the dishes among the chefs such that the maximum workload of any chef is minimized.
Args:
m (int): The number of dishes.
n (int): The number of chefs.
dishes (List[int]): The list where the i-th element represents the ... | def canDistribute(dishes, m, n, max_workload):
chefs = 1
current_workload = 0
for time in dishes:
if current_workload + time <= max_workload:
current_workload += time
else:
chefs += 1
current_workload = time
if chefs > n:
r... | def test_minMaxWorkload_single_chef():
assert minMaxWorkload(5, 1, [2, 4, 6, 8, 10]) == 30
def test_minMaxWorkload_equal_dishes_chefs():
assert minMaxWorkload(4, 4, [1, 2, 3, 4]) == 4
def test_minMaxWorkload_more_dishes_than_chefs():
assert minMaxWorkload(10, 4, [11, 6, 5, 4, 7, 3, 10, 8, 3, 1]) == 17
de... | [
{
"docstring": null,
"function_declaration": "def canDistribute(dishes, m, n, max_workload):",
"function_name": "canDistribute",
"parameter_list": "(dishes, m, n, max_workload)"
},
{
"docstring": null,
"function_declaration": "def minMaxWorkload(m, n, dishes):",
"function_name": "min... | [
1,
0,
0,
1,
1,
0,
0,
0,
0,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def minimize_max_workload(m, n, dish_times):\n def canDistribute(target_max_workload):\n current_sum = 0\n chefs_needed = 1\n \n ... | trial_gpt4o_9 | {
"original_instruction": "A new kitchen management system is being developed for a restaurant. Each chef is responsible for a specific number of dishes each day. The head chef assigns dishes to each chef based on their workload capacity. Your task is to create a program that helps to uniformly distribute dishes amon... | 0.676551 | Codeforces_19630 | C | [
"canDistribute",
"minMaxWorkload"
] | 2 | [
[
"minMaxWorkload",
"canDistribute"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 4a7e4a70aaf6d76c92454442ad9fd9a027982418 | fde8fb1669aebadc1aac1fadd9abaaa62b579676 | |||
v1.0 | complete | Codeforces | Codeforces_19730_C | def solve_magic_forest(n, magic_numbers, roads, queries):
""" In a faraway land, there is a magical forest with n distinct trees. Each tree holds a unique integer value in its bark, known as the tree's magic number. The trees are connected by n-1 bidirectional roads, forming a single connected forest with exactly o... | def dfs(tree, node, parent, magic_numbers, subtree_sum):
"""
Perform DFS to compute subtree sum for each node.
"""
subtree_sum[node] = magic_numbers[node]
for neighbor in tree[node]:
if neighbor != parent:
dfs(tree, neighbor, node, magic_numbers, subtree_sum)
subtree_... | def test_solve_magic_forest():
n = 5
magic_numbers = [1, 2, 3, 4, 5]
roads = [(0, 1), (1, 2), (1, 3), (3, 4)]
queries = [(0, 4), (2, 3), (1, 1)]
expected = [15, 9, 2]
assert solve_magic_forest(n, magic_numbers, roads, queries) == expected
n = 3
magic_numbers = [10, 20, 30]
roads = [... | [
{
"docstring": "Perform DFS to compute subtree sum for each node.",
"function_declaration": "def dfs(tree, node, parent, magic_numbers, subtree_sum):",
"function_name": "dfs",
"parameter_list": "(tree, node, parent, magic_numbers, subtree_sum)"
},
{
"docstring": null,
"function_declarati... | [
0,
0,
1,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import defaultdict\n\n# Function to perform DFS and compute necessary information\ndef dfs(node, parent, adjacency_list, magic_numbers, depth... | trial_gpt4o_2 | {
"original_instruction": "In a faraway land, there is a magical forest with n distinct trees. Each tree holds a unique integer value in its bark, known as the tree's magic number. The trees are connected by n-1 bidirectional roads, forming a single connected forest with exactly one path between any pair of trees.\n\... | 0.561284 | Codeforces_19730 | C | [
"dfs",
"solve_magic_forest"
] | 2 | [
[
"solve_magic_forest",
"dfs"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | e000719109fe46c68a75880a77eea3d89a956a35 | 26712773a1bf1cb58080291eec535781cd398716 | |||
v1.0 | complete | Codeforces | Codeforces_19898_C | from typing import List, Tuple
def add_extra_edge_to_minimize_diameter(n: int, edges: List[Tuple[int, int]]) -> Tuple[int, int]:
"""
Adds an extra edge to minimize the diameter of the tree.
Returns the two nodes a and b to which the edge should be added.
>>> add_extra_edge_to_minimize_diameter(4, ... | from collections import deque
def find_farthest_node(tree, start_node):
"""
Performs a BFS to find the farthest node from the start_node.
Returns the farthest node and its distance.
"""
n = len(tree)
visited = [False] * n
dist = [-1] * n
queue = deque([start_node])
visited[start_nod... | from solution import add_extra_edge_to_minimize_diameter
def test_case_1():
n = 4
edges = [(1, 2), (1, 3), (3, 4)]
assert add_extra_edge_to_minimize_diameter(n, edges) in [(2, 4), (4, 2)]
def test_case_2():
n = 5
edges = [(1, 2), (1, 3), (2, 4), (3, 5)]
assert add_extra_edge_to_minimize_diamet... | [
{
"docstring": "Performs a BFS to find the farthest node from the start_node.\nReturns the farthest node and its distance.",
"function_declaration": "def find_farthest_node(tree, start_node):",
"function_name": "find_farthest_node",
"parameter_list": "(tree, start_node)"
},
{
"docstring": "F... | [
0,
1,
0,
0,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import deque, defaultdict\n\ndef find_best_edge(n, edges):\n def bfs(start):\n dist = [-1] * (n + 1)\n dist[start] = 0\n ... | trial_gpt4o_1 | {
"original_instruction": "Peter is designing a new routing protocol for a network consisting of $$$n$$$ nodes labeled from $$$1$$$ to $$$n$$$. The network is represented as a tree. Each node can communicate directly with its adjacent nodes. We will denote this tree as $$$\\mathcal{T}$$$.\n\nTo improve the efficiency... | 0.6635 | Codeforces_19898 | C | [
"find_farthest_node",
"find_diameter",
"add_extra_edge_to_minimize_diameter"
] | 3 | [
[
"add_extra_edge_to_minimize_diameter",
"find_diameter"
],
[
"find_diameter",
"find_farthest_node"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | dc817e4544d3d8070f02827ed317c43330ab59f9 | f9cc17f697f6fdea526eebd7bcba013abb234b74 | |||
v1.0 | complete | Codeforces | Codeforces_19873_C | from typing import List, Tuple
def shortest_travel_time_and_path(n: int, m: int, routes: List[Tuple[int, int, int]]) -> Tuple[int, List[int]]:
""" Find the shortest travel time and its path in Berland's subway system from station 1 to station n.
:param n: Number of stations
:param m: Number of routes
... | import heapq
def find_shortest_path(n, m, routes):
graph = {i: [] for i in range(1, n+1)}
for ai, bi, ti in routes:
graph[ai].append((bi, ti))
graph[bi].append((ai, ti))
# Dijkstra's algorithm
pq = [(0, 1, [])] # (accumulated cost, current station, path)
shortest_paths = {i: f... | from solution import shortest_travel_time_and_path
def test_shortest_travel_time_and_path():
n = 4
m = 5
routes = [
(1, 2, 3),
(1, 3, 6),
(2, 3, 1),
(3, 4, 2),
(2, 4, 5),
]
shortest_time, path = shortest_travel_time_and_path(n, m, routes)
assert shortest_... | [
{
"docstring": null,
"function_declaration": "def find_shortest_path(n, m, routes):",
"function_name": "find_shortest_path",
"parameter_list": "(n, m, routes)"
},
{
"docstring": null,
"function_declaration": "def shortest_travel_time_and_path(n, m, routes):",
"function_name": "shorte... | [
1,
1,
1,
0,
0,
1,
0,
1,
0
] | 5 | medium | 0.556 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import heapq\n\ndef find_shortest_path(n, m, routes):\n # Create adjacency list\n graph = {i: [] for i in range(1, n + 1)}\n for a, b, t in routes:\n... | trial_gpt4o_8 | {
"original_instruction": "Berland's subway system consists of n stations and m routes. Each route connects a pair of stations and has an associated travel time ti, which represents the time it takes for a train to travel from one station to the other along that route. Each route is bidirectional, meaning that trains... | 0.643086 | Codeforces_19873 | C | [
"find_shortest_path",
"shortest_travel_time_and_path"
] | 2 | [
[
"shortest_travel_time_and_path",
"find_shortest_path"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3d45dba3a5e9650091da082bac29db386bd23b87 | f3063ce01fed21f813c0aebfb03d2648520cd0ec | |||
v1.0 | complete | Codeforces | Codeforces_19956_C | from typing import List, Tuple
def hamiltonian_path_exists(n: int, m: int, edges: List[Tuple[int, int]]) -> bool:
""" Determine if there is a Hamiltonian path in the given graph.
Args:
n (int): Number of vertices.
m (int): Number of edges.
edges (List[Tuple[int, int]]): List of edges r... | def hamiltonian_path_exists(n, m, edges):
from itertools import permutations
# Generate adjacency matrix
adj = [[0] * n for _ in range(n)]
for u, v in edges:
adj[u-1][v-1] = 1
adj[v-1][u-1] = 1
# Check all permutations of vertices to see if any is a hamiltonian path
for... | def test_hamiltonian_path_exists():
# Test case 1
assert hamiltonian_path_exists(4, 4, [(1, 2), (2, 3), (3, 4), (4, 1)]) == True
# Test case 2
assert hamiltonian_path_exists(4, 3, [(1, 2), (2, 3), (3, 4)]) == True
# Test case 3
assert hamiltonian_path_exists(4, 3, [(1, 2), (2, 3), (3, 1)]) == Fa... | [
{
"docstring": null,
"function_declaration": "def hamiltonian_path_exists(n, m, edges):",
"function_name": "hamiltonian_path_exists",
"parameter_list": "(n, m, edges)"
},
{
"docstring": null,
"function_declaration": "def solve(n, m, edges):",
"function_name": "solve",
"parameter_... | [
0,
0,
0,
0,
1,
0,
0,
1,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def has_hamiltonian_path(n, m, edges):\n from itertools import permutations\n \n if n == 1:\n return \"YES\"\n\n graph = {i: set() for i in... | trial_gpt4o_7 | {
"original_instruction": "You are given a simple undirected graph with \"n\" vertices and \"m\" edges. Each vertex of the graph has a unique integer identifier from 1 to n. Your task is to determine if there is a simple path in the graph that visits each vertex exactly once.\n\nThe input to the program will be two i... | 0.558737 | Codeforces_19956 | C | [
"hamiltonian_path_exists",
"solve"
] | 2 | [
[
"solve",
"hamiltonian_path_exists"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 3858bf6adcb64d07a216b15fec61e1917acd33f4 | ee659889361d6d6662bdb3f1374486fcd570a0c3 | |||
v1.0 | complete | Codeforces | Codeforces_19729_C | def is_power_of_2(x):
"""
Check if a number is a power of 2.
"""
return x > 0 and (x & (x - 1)) == 0
def longest_power_of_2_subsequence(test_cases):
"""
Given an array of integers, find the longest contiguous subsequence such that every element
in this subsequence is a power of 2. If there... | def is_power_of_2(x):
"""
Check if a number is a power of 2.
"""
return x > 0 and (x & (x - 1)) == 0
def longest_power_of_2_subsequence(test_cases):
results = []
for case in test_cases:
n, array = case
max_length = 0
current_length = 0
for num in array:
... | import pytest
from solution import longest_power_of_2_subsequence
def test_example_cases():
test_cases = [
(8, [1, 2, 3, 4, 8, 16, 32, 2]),
(5, [5, 3, 6, 7, 9]),
(6, [4, 8, 2, 4, 16, 2])
]
expected = [5, 0, 6]
assert longest_power_of_2_subsequence(test_cases) == expected
def te... | [
{
"docstring": "Check if a number is a power of 2.",
"function_declaration": "def is_power_of_2(x):",
"function_name": "is_power_of_2",
"parameter_list": "(x)"
},
{
"docstring": null,
"function_declaration": "def longest_power_of_2_subsequence(test_cases):",
"function_name": "longest... | [
1,
0,
1,
0,
1,
0,
0,
1,
1,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_power_of_two(x):\n \"\"\"\n Checks if a number x is a power of two.\n \"\"\"\n return x > 0 and (x & (x - 1)) == 0\n\ndef longest_power_of_... | trial_gpt4o_9 | {
"original_instruction": "Given an array of integers, your task is to find the longest contiguous subsequence such that every element in this subsequence is a power of 2. If there are multiple subsequences with the same maximum length, return the one that appears first.\n\n### Input\nThe first line of the input cont... | 0.605756 | Codeforces_19729 | C | [
"is_power_of_2",
"longest_power_of_2_subsequence"
] | 2 | [
[
"longest_power_of_2_subsequence",
"is_power_of_2"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a417ac5a55a0bebf0d37651e172dceb17f578476 | 30a0bde4562f3704a0a84154a23f96eba9223dfa | |||
v1.0 | complete | Codeforces | Codeforces_19756_C | def find_max_plus_length(n: int, m: int, grid: List[List[int]]) -> int:
""" Determine the maximum arm length for any valid "plus"-shaped figure in the grid.
>>> find_max_plus_length(4, 5, [
... [1, 0, 0, 1, 0],
... [1, 1, 1, 1, 1],
... [0, 1, 0, 1, 0],
... [1, 1, 1, 1, 0]
...... | def max_plus_length(grid):
n = len(grid)
m = len(grid[0])
up = [[0] * m for _ in range(n)]
down = [[0] * m for _ in range(n)]
left = [[0] * m for _ in range(n)]
right = [[0] * m for _ in range(n)]
for i in range(n):
for j in range(m):
if grid[i][j] == 1:
... | import pytest
from solution import find_max_plus_length
def test_example_1():
grid = [
[1, 0, 0, 1, 0],
[1, 1, 1, 1, 1],
[0, 1, 0, 1, 0],
[1, 1, 1, 1, 0]
]
assert find_max_plus_length(4, 5, grid) == 1
def test_example_2():
grid = [
[1, 0, 1],
[0, 1, 0],
... | [
{
"docstring": null,
"function_declaration": "def max_plus_length(grid):",
"function_name": "max_plus_length",
"parameter_list": "(grid)"
},
{
"docstring": null,
"function_declaration": "def find_max_plus_length(n, m, grid):",
"function_name": "find_max_plus_length",
"parameter_l... | [
1,
1,
1,
1,
0,
0,
1,
0,
1,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def largest_plus_arm_length(grid):\n n = len(grid)\n m = len(grid[0])\n\n def get_dp():\n left = [[0] * m for _ in range(n)]\n right = ... | trial_gpt4o_9 | {
"original_instruction": "Sara has a peculiar grid. The grid is a rectangle consisting of n rows and m columns. Each cell in the grid can contain one of two possible values: 0 or 1. Adjacent cells can have the same or different values. Sara wants to know the largest \"plus\" shape she can find in the grid. A \"plus\... | 0.523245 | Codeforces_19756 | C | [
"max_plus_length",
"find_max_plus_length"
] | 2 | [
[
"find_max_plus_length",
"max_plus_length"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | cd2712fd33c3634ce36ebc0c904c7292d05f2a07 | bf706fe6e624e20e0503713c63244adeec97e789 | |||
v1.0 | complete | Codeforces | Codeforces_19919_C | from typing import List, Tuple
def minimum_lights(n: int, m: int, edges: List[Tuple[int, int, int]]) -> int:
"""
Determine the minimum number of lights needed to ensure that every landmark is lit.
:param n: Number of landmarks
:param m: Number of paths
:param edges: List of tuples representing... | def find(parent, i):
if parent[i] == i:
return i
return find(parent, parent[i])
def union(parent, rank, x, y):
xroot = find(parent, x)
yroot = find(parent, y)
if rank[xroot] < rank[yroot]:
parent[xroot] = yroot
elif rank[xroot] > rank[yroot]:
parent[yroot] = xroot
el... | from solution import minimum_lights
def test_example():
n = 4
m = 4
edges = [(1, 2, 1), (2, 3, 2), (3, 4, 1), (4, 1, 2)]
assert minimum_lights(n, m, edges) == 3
def test_disconnected_graph():
n = 3
m = 1
edges = [(1, 2, 5)]
assert minimum_lights(n, m, edges) == 1
def test_single_node(... | [
{
"docstring": null,
"function_declaration": "def find(parent, i):",
"function_name": "find",
"parameter_list": "(parent, i)"
},
{
"docstring": null,
"function_declaration": "def union(parent, rank, x, y):",
"function_name": "union",
"parameter_list": "(parent, rank, x, y)"
},
... | [
0,
1,
1,
1,
0,
0,
1,
1,
1,
0
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def minimum_lights_needed(n, m, paths):\n if n == 1:\n return 0 # Only one landmark, no light is needed.\n \n # A MATLAB-based approach to fi... | trial_gpt4o_6 | {
"original_instruction": "A park contains several paths, each connecting a pair of landmarks within the park. Each path has a certain distance associated with it. The park administration wants to install lights on the paths to ensure that every landmark is directly or indirectly lit by at least one light. However, d... | 0.632191 | Codeforces_19919 | C | [
"find",
"union",
"minimum_lights"
] | 3 | [
[
"minimum_lights",
"find"
],
[
"minimum_lights",
"union"
],
[
"union",
"find"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 24353edacbe4b8ae6bf5d81e71957e3dc73de4dc | 7c63dcb2c907a9565b59b0637ad4a4ad6c2b64a4 | |||
v1.0 | complete | Codeforces | Codeforces_19889_C | def transform_array(m, b):
"""Transform the given array into a non-decreasing array.
The transformation is done using specific subarray reverse operations.
Args:
m (int): The number of elements in array b.
b (List[int]): The array of integers.
Returns:
List[Union[int, Tuple[int, int]]]: Th... | def is_non_decreasing(arr):
"""
Checks if the given array is non-decreasing.
"""
return all(arr[i] <= arr[i + 1] for i in range(len(arr) - 1))
def reverse_subarray(arr, i, j):
"""
Returns a new array with the subarray from index i to j reversed.
"""
return arr[:i] + arr[i:j + 1][::-1] +... | from solution import transform_array
def test_transform_array_case_1():
m = 5
b = [4, 3, 2, 1, 5]
result = transform_array(m, b)
assert result[0] > 0 # At least one operation must be performed
final_array = b[:]
for op in result[1:]:
i, j = op
final_array[i-1:j] = reversed(fina... | [
{
"docstring": "Checks if the given array is non-decreasing.",
"function_declaration": "def is_non_decreasing(arr):",
"function_name": "is_non_decreasing",
"parameter_list": "(arr)"
},
{
"docstring": "Returns a new array with the subarray from index i to j reversed.",
"function_declarati... | [
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def make_non_decreasing(m, b):\n operations = []\n for i in range(1, m):\n if b[i-1] > b[i]:\n j = i\n while j < m and (sum... | trial_gpt4o_9 | {
"original_instruction": "You are given an array b[1], b[2], ..., b[m] containing m integers. Your task is to transform this array into a non-decreasing array using the following operation (you may need to apply it multiple times):\n\n- Select two indices i and j (1 ≤ i < j ≤ m) such that the sum of the subarray b[i... | 0.664435 | Codeforces_19889 | C | [
"is_non_decreasing",
"reverse_subarray",
"sum_is_even",
"make_non_decreasing",
"transform_array"
] | 5 | [
[
"make_non_decreasing",
"is_non_decreasing"
],
[
"make_non_decreasing",
"reverse_subarray"
],
[
"make_non_decreasing",
"sum_is_even"
],
[
"transform_array",
"make_non_decreasing"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 1ad05142a49b07877d6ad6feeeba28b63e0df8bf | a560d8a7d6d9ae3da87b3f2a63eb2377a0fd306a | |||
v1.0 | complete | Codeforces | Codeforces_19926_C | def minimum_travel_time(n: int, m: int, road_data: List[Tuple[int, int, int]], k: int, teleport_data: List[Tuple[int, int]]) -> List[int]:
""" Determine the minimum travel time from the capital to each city in a kingdom with roads and teleportation.
Parameters:
- n (int): Number of cities
- m (int)... | import heapq
def dijkstra(n, roads, teleports, source=1):
# Initialization
graph = {i: [] for i in range(1, n + 1)}
# Adding roads to graph
for u, v, w in roads:
graph[u].append((w, v))
graph[v].append((w, u))
# Adding teleportation pairs to graph with weight 0
for x, ... | def test_minimum_travel_time():
n = 5
m = 6
road_data = [
(1, 2, 2),
(1, 3, 3),
(2, 4, 4),
(3, 4, 1),
(4, 5, 5),
(3, 5, 8)
]
k = 1
teleport_data = [
(1, 5)
]
result = minimum_travel_time(n, m, road_data, k, teleport_data)
assert... | [
{
"docstring": null,
"function_declaration": "def dijkstra(n, roads, teleports, source=1):",
"function_name": "dijkstra",
"parameter_list": "(n, roads, teleports, source=1)"
},
{
"docstring": null,
"function_declaration": "def minimum_travel_time(n, m, road_data, k, teleport_data):",
... | [
1,
0,
0,
0,
1,
1,
0,
0,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import heapq\n\ndef dijkstra(n, adj, start=1):\n dist = [float('inf')] * (n + 1)\n dist[start] = 0\n pq = [(0, start)] # (distance, node)\n while... | trial_gpt4o_5 | {
"original_instruction": "In a distant land, there exists a kingdom with n cities, connected by m bidirectional roads. Each road has a positive integer weight representing the time it takes to travel between the two cities it connects. However, there is a powerful sorcerer in the kingdom who can teleport between cer... | 0.715934 | Codeforces_19926 | C | [
"dijkstra",
"minimum_travel_time"
] | 2 | [
[
"minimum_travel_time",
"dijkstra"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | be9b1947c6055d693ad9370e58e6d00e19c93ce0 | 46fc3fd8e245320e6eccd14356276f75200e5af7 | |||
v1.0 | complete | Codeforces | Codeforces_19986_C | import math
from typing import List, Tuple
def optimal_garbage_collection(n: int, coordinates: List[Tuple[int, int]]) -> float:
"""Determine the optimal route for a garbage truck to empty all bins and return to the starting point.
The route should minimize the total distance traveled.
Args:
n: An ... | import itertools
import math
def euclidean_distance(point1, point2):
return math.sqrt((point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2)
def optimal_garbage_collection(n, coordinates):
all_permutations = itertools.permutations(coordinates)
min_distance = float('inf')
for perm in all_permuta... | from solution import optimal_garbage_collection
def test_optimal_garbage_collection_example():
coordinates = [(0, 0), (2, 0), (2, 2), (0, 2)]
assert optimal_garbage_collection(4, coordinates) == 8.0000
def test_optimal_garbage_collection_case1():
coordinates = [(0, 0), (1, 0), (1, 1), (0, 1)]
assert o... | [
{
"docstring": null,
"function_declaration": "def euclidean_distance(point1, point2):",
"function_name": "euclidean_distance",
"parameter_list": "(point1, point2)"
},
{
"docstring": null,
"function_declaration": "def optimal_garbage_collection(n, coordinates):",
"function_name": "opt... | [
0,
0,
0,
0,
0,
1,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import itertools\nimport math\n\ndef calculate_distance(point1, point2):\n return math.sqrt((point2[0] - point1[0]) ** 2 + (point2[1] - point1[1]) ** 2)\n\... | trial_gpt4o_5 | {
"original_instruction": "### Automated Garbage Collection Optimization\n\nThe city council has decided to implement a new automated system for managing garbage collection routes. Each day, smart garbage trucks will follow a specific route that maximizes efficiency, such as minimizing the total distance traveled whi... | 0.568912 | Codeforces_19986 | C | [
"euclidean_distance",
"optimal_garbage_collection"
] | 2 | [
[
"optimal_garbage_collection",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9bf80a50bb647845d538f012d2edc6043a08382c | 53f99c35fbef5bb68308fac369cbcfec7ab7041e | |||
v1.0 | complete | Codeforces | Codeforces_4965_C | def rotateArray(arr: List[int], k: int) -> List[int]:
"""
You are given an integer array `arr` and an integer `k`, which represents the number of steps to rotate the array to the right. Write a function `rotateArray` to rotate the array in-place and return the modified array.
Parameters:
arr: A list of... | from typing import List
def rotateArray(arr: List[int], k: int) -> List[int]:
"""
Rotates the array `arr` in-place `k` steps to the right.
"""
n = len(arr)
if n == 0:
return arr
# Ensure k is within the bounds of the array length
k = k % n
# Rotate the array in three s... | from solution import rotateArray
def test_rotate_zero_steps():
assert rotateArray([1, 2, 3, 4, 5], 0) == [1, 2, 3, 4, 5]
def test_rotate_small_array():
assert rotateArray([1], 3) == [1]
def test_rotate_normal_case():
assert rotateArray([1, 2, 3, 4, 5], 2) == [4, 5, 1, 2, 3]
def test_rotate_case_with_k_e... | [
{
"docstring": "Rotates the array `arr` in-place `k` steps to the right.",
"function_declaration": "def rotateArray(arr, k):",
"function_name": "rotateArray",
"parameter_list": "(arr, k)"
},
{
"docstring": null,
"function_declaration": "def reverse(arr, start, end):",
"function_name"... | [
0,
1,
0,
0,
1,
1,
0,
1,
1,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef rotateArray(arr: List[int], k: int) -> List[int]:\n n = len(arr)\n if n == 0:\n return arr\n k = k % n # Handl... | trial_gpt4o_9 | {
"original_instruction": "You are given an integer array `arr` and an integer `k`, which represents the number of steps to rotate the array to the right. Write a function `rotateArray` to rotate the array in-place and return the modified array.\n\n### Function Signature\n```python\ndef rotateArray(arr: List[int], k:... | 0.709446 | Codeforces_4965 | C | [
"rotateArray",
"reverse"
] | 2 | [
[
"rotateArray",
"reverse"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e7480a11c7d48d9c36289cac0b987d3623e49a1b | 0595423d04d89d0367c1014141db6039df25f67b | |||
v1.0 | complete | Codeforces | Codeforces_5084_C | def minimum_cost(n: int, m: int, edges: List[Tuple[int, int, int]]) -> int:
""" Computes the minimum cost to connect all computers in a network.
Parameters:
n (int): Number of computers (nodes)
m (int): Number of connections (edges)
edges (List[Tuple[int, int, int]]): List of tuples representin... | def find(parent, x):
if parent[x] != x:
parent[x] = find(parent, parent[x])
return parent[x]
def union(parent, rank, x, y):
rootX = find(parent, x)
rootY = find(parent, y)
if rootX != rootY:
if rank[rootX] > rank[rootY]:
parent[rootY] = rootX
elif rank[rootX] < r... | from solution import minimum_cost
def test_minimum_cost_sample_1():
n = 4
m = 5
edges = [
(1, 2, 1),
(1, 3, 2),
(2, 3, 2),
(2, 4, 3),
(3, 4, 3)
]
assert minimum_cost(n, m, edges) == 6
def test_minimum_cost_sample_2():
n = 3
m = 0
edges = []
a... | [
{
"docstring": null,
"function_declaration": "def find(parent, x):",
"function_name": "find",
"parameter_list": "(parent, x)"
},
{
"docstring": null,
"function_declaration": "def union(parent, rank, x, y):",
"function_name": "union",
"parameter_list": "(parent, rank, x, y)"
},
... | [
0,
0,
1,
0,
1,
0,
1,
0,
0,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def find(parent, i):\n if parent[i] == i:\n return i\n else:\n return find(parent, parent[i])\n\ndef union(parent, rank, x, y):\n root_... | trial_gpt4o_4 | {
"original_instruction": "Consider a network of computers with n nodes (computers) and m edges (connections). Each connection between two computers has an associated cost (representing the cost to establish a direct communication between them). Your task is to find the minimum cost to connect all the computers in su... | 0.616852 | Codeforces_5084 | C | [
"find",
"union",
"kruskal",
"minimum_cost"
] | 4 | [
[
"kruskal",
"find"
],
[
"kruskal",
"union"
],
[
"minimum_cost",
"kruskal"
],
[
"union",
"find"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 7bc5104fb8f8125ce551940bd8a67c90200f0983 | b8633a4da013e9dde64a7b61416ce514dfd52536 | |||
v1.0 | complete | Codeforces | Codeforces_16731_C | def count_unique_islands(n: int, m: int, grid: List[List[int]]) -> int:
"""
Given a grid of n rows and m columns, where each cell contains either a 0 or a 1,
returns the number of unique islands in the grid.
An island is defined as a group of connected 1s (connected horizontally or vertically).
Tw... | def find_unique_islands(grid):
"""
Returns the number of unique islands in the grid.
"""
n = len(grid)
m = len(grid[0])
def dfs(x, y, base_x, base_y, island):
if x < 0 or x >= n or y < 0 or y >= m or grid[x][y] == 0:
return
grid[x][y] = 0 # Mark as visited
i... | from solution import count_unique_islands
def test_example_1():
grid = [
[1, 1, 0, 0, 0],
[1, 0, 0, 1, 1],
[0, 0, 0, 1, 0],
[1, 1, 0, 0, 0]
]
assert count_unique_islands(4, 5, grid) == 2
def test_example_2():
grid = [
[1, 1, 1],
[1, 0, 1],
[1, 1,... | [
{
"docstring": "Returns the number of unique islands in the grid.",
"function_declaration": "def find_unique_islands(grid):",
"function_name": "find_unique_islands",
"parameter_list": "(grid)"
},
{
"docstring": "Wrapper function to handle input and output\nReturns the number of unique island... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def num_unique_islands(grid):\n def dfs(r, c, r0, c0):\n # Traverse the island and record the relative position of each cell\n grid[r][c] = 0... | trial_gpt4o_9 | {
"original_instruction": "You are given a grid consisting of $$$n$$$ rows and $$$m$$$ columns ($$$1 \\leq n, m \\leq 1000$$$). Each cell in the grid either contains a **0** or a **1**. Your task is to count the number of unique islands in the grid. An island is defined as a group of connected **1s** (cells containin... | 0.592424 | Codeforces_16731 | C | [
"find_unique_islands",
"count_unique_islands"
] | 2 | [
[
"count_unique_islands",
"find_unique_islands"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0bc56bf5df3b9fa59dd3e9f3ada65b4a5ceb8dcc | c3b315546070091dfd776781c3b4c496445917a7 | |||
v1.0 | complete | Codeforces | Codeforces_5311_C | from typing import List
def find_subarray_with_max_sum(arr: List[int]) -> int:
"""
Finds and returns the sum of the contiguous subarray with the largest sum.
Parameters:
arr (list): A list of integers.
Returns:
int: The maximum sum of the contiguous subarray.
Examples:
>>> find_subar... | def find_subarray_with_max_sum(arr):
"""
Finds and returns the sum of the contiguous subarray with the largest sum.
Parameters:
arr (list): A list of integers.
Returns:
int: The maximum sum of the contiguous subarray.
"""
max_end_here = max_so_far = arr[0]
for num in arr[1:]:
... | from solution import find_subarray_with_max_sum, process_input_and_find_max_sum
def test_single_element():
assert find_subarray_with_max_sum([1]) == 1
assert find_subarray_with_max_sum([-1]) == -1
def test_all_negative():
assert find_subarray_with_max_sum([-2, -3, -4, -1]) == -1
def test_mixed_elements()... | [
{
"docstring": "Finds and returns the sum of the contiguous subarray with the largest sum.\n\nParameters:\narr (list): A list of integers.\n\nReturns:\nint: The maximum sum of the contiguous subarray.",
"function_declaration": "def find_subarray_with_max_sum(arr):",
"function_name": "find_subarray_with_... | [
0,
1,
0,
1,
0,
0,
1,
1,
0,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def find_subarray_with_max_sum(array):\n \"\"\"\n Finds the sum of the contiguous subarray within a one-dimensional numeric list\n which has the larg... | trial_gpt4o_9 | {
"original_instruction": "You are given a list of integers. Write a function `find_subarray_with_max_sum` that finds a contiguous subarray with the largest sum, and returns this sum. Consider the case where the list can contain both positive and negative integers. \n\nFor example, given the array: [-2, -3, 4, -1, -2... | 0.707112 | Codeforces_5311 | C | [
"find_subarray_with_max_sum",
"process_input_and_find_max_sum"
] | 2 | [
[
"process_input_and_find_max_sum",
"find_subarray_with_max_sum"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8808fc8a58d103afb0899f31203d9d11dae206c5 | 14fbc269bd262e86eb3c560b419791744b61edd0 | |||
v1.0 | complete | Codeforces | Codeforces_6687_C | from typing import List
def sequence_prime_sum(n: int, array: List[int]) -> str:
"""
Determine if it's possible to rearrange the array such that the sum of any two
consecutive elements is a prime number.
>>> sequence_prime_sum(3, [1, 2, 3])
'YES\n2 1 3'
>>> sequence_prime_sum(4, [4, 6, 8, ... | from itertools import permutations
def is_prime(n):
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True
def can_re... | from solution import sequence_prime_sum
def test_sequence_prime_sum_example1():
n = 3
array = [1, 2, 3]
assert sequence_prime_sum(n, array).startswith("YES")
def test_sequence_prime_sum_example2():
n = 4
array = [4, 6, 8, 10]
assert sequence_prime_sum(n, array) == "NO"
def test_sequence_prime... | [
{
"docstring": null,
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def can_rearrange_with_prime_sums(arr):",
"function_name": "can_rearrange_with_prime_sums",
"parameter_list": "(a... | [
0,
0,
1,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\" Helper function to check if a number is prime \"\"\"\n if n <= 1:\n return False\n if n == 2:\n return True\n... | trial_gpt4o_2 | {
"original_instruction": "Alex loves sequences of numbers. Specifically, Alex is fascinated by sequences where the sum of any two adjacent elements is prime. You are given an integer array and need to determine if it's possible to rearrange the array such that it meets Alex's condition.\n\nGiven an array of integers... | 0.734839 | Codeforces_6687 | C | [
"is_prime",
"can_rearrange_with_prime_sums",
"sequence_prime_sum"
] | 3 | [
[
"can_rearrange_with_prime_sums",
"is_prime"
],
[
"sequence_prime_sum",
"can_rearrange_with_prime_sums"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | ecfd7465b8bc1f15fb29f5eb320a8fb398cfb3b3 | 8f560a8a3a7f30de94d7954af98741db45a15f84 | |||
v1.0 | complete | Codeforces | Codeforces_7051_C | from typing import List
def process_test_cases(test_cases: List[List[int]]) -> List[int]:
""" Given an array of integers, returns the number of inversions for each test case.
An inversion is defined as a case where i < j and arr[i] > arr[j].
>>> process_test_cases([[2, 3, 8, 6, 1]])
[5]
>... | def merge_and_count(arr, temp_arr, left, mid, right):
i = left # Starting index for left subarray
j = mid + 1 # Starting index for right subarray
k = left # Starting index to be sorted
inv_count = 0
while i <= mid and j <= right:
if arr[i] <= arr[j]:
temp_arr[k] = arr[i]
... | import pytest
from solution import process_test_cases
def test_single_inversion():
assert process_test_cases([[1, 2, 3, 4, 5]]) == [0]
assert process_test_cases([[5, 4, 3, 2, 1]]) == [10]
def test_multiple_inversions():
assert process_test_cases([[2, 3, 8, 6, 1]]) == [5]
assert process_test_cases([[5,... | [
{
"docstring": null,
"function_declaration": "def merge_and_count(arr, temp_arr, left, mid, right):",
"function_name": "merge_and_count",
"parameter_list": "(arr, temp_arr, left, mid, right)"
},
{
"docstring": null,
"function_declaration": "def merge_sort_and_count(arr, temp_arr, left, r... | [
0,
1,
1,
1,
1,
1,
0,
1,
1,
0
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def count_inversions(arr):\n \"\"\"\n Counts the number of inversions in the array using a modified merge sort algorithm.\n \"\"\"\n def merge_cou... | trial_gpt4o_8 | {
"original_instruction": "You are given an array of integers where each integer can be positive, negative, or zero. We define an \"inversion\" in the array such that if we have two indices \\(i\\) and \\(j\\) with \\(i < j\\), then an inversion occurs if \\(arr[i] > arr[j]\\). Your task is to find the total number o... | 0.804556 | Codeforces_7051 | C | [
"merge_and_count",
"merge_sort_and_count",
"count_inversions",
"process_test_cases"
] | 4 | [
[
"count_inversions",
"merge_sort_and_count"
],
[
"merge_sort_and_count",
"merge_and_count"
],
[
"process_test_cases",
"count_inversions"
]
] | 3 | [
"process_test_cases"
] | false | [] | false | pytest | true | [] | true | ff3339e0fc1b2baf7eb5d0c46b7180235b16fe4c | 0005268d85dde3fd923e7ecc274b1d874995a687 | |||
v1.0 | complete | Codeforces | Codeforces_7385_C | from typing import List, Tuple
def maximum_spanning_tree(n: int, edges: List[Tuple[int, int, int]]) -> int:
"""
Determine the maximum possible sum of edge weights in a valid tree that includes every node exactly once.
Args:
n: The number of nodes.
edges: A list of tuples where each tuple contains... | def find(parent, i):
if parent[i] == i:
return i
else:
parent[i] = find(parent, parent[i])
return parent[i]
def union(parent, rank, x, y):
xroot = find(parent, x)
yroot = find(parent, y)
if rank[xroot] < rank[yroot]:
parent[xroot] = yroot
elif rank[xroot] > rank... | def test_example():
n = 4
edges = [
(1, 2, 3),
(1, 3, 2),
(2, 3, 4),
(3, 4, 1),
(2, 4, 5)
]
assert maximum_spanning_tree(n, edges) == 12
def test_single_node():
n = 1
edges = []
assert maximum_spanning_tree(n, edges) == 0
def test_no_edges():
n =... | [
{
"docstring": null,
"function_declaration": "def find(parent, i):",
"function_name": "find",
"parameter_list": "(parent, i)"
},
{
"docstring": null,
"function_declaration": "def union(parent, rank, x, y):",
"function_name": "union",
"parameter_list": "(parent, rank, x, y)"
},
... | [
1,
0,
0,
0,
0,
0,
0,
1,
1,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def maximum_weighted_tree_sum(n, m, edges):\n \"\"\"\n Finds the maximum possible sum of edge weights in a valid tree that includes every node exactly o... | trial_gpt4o_8 | {
"original_instruction": "Marie wants to organize a workshop for children where they will learn about constructing networks. She has a set of nodes and wants to connect them using edges. Each edge has a certain weight and each node can only be connected to at most two other nodes, forming a tree-like structure.\n\nG... | 0.735499 | Codeforces_7385 | C | [
"find",
"union",
"maximum_spanning_tree"
] | 3 | [
[
"maximum_spanning_tree",
"find"
],
[
"maximum_spanning_tree",
"union"
],
[
"union",
"find"
]
] | 3 | [] | false | [] | false | pytest | false | [] | true | 8d80024d8f11e91826543746e630f79e239d2df4 | 18507ffa45279325e980187f2df2b2e6ca55e6f6 | |||
v1.0 | complete | Codeforces | Codeforces_7447_C | def find_shortest_path(n: int, m: int, grid: List[List[int]]) -> int:
"""
You are given a city grid and it's represented as a 2D array. Each cell in the 2D array represents a city block.
The value of the cell can either be 0 (representing an obstacle) or 1 (representing an accessible path).
A person c... | from collections import deque
def shortest_path_in_grid(grid):
n = len(grid)
m = len(grid[0])
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
def in_bounds(x, y):
return 0 <= x < n and 0 <= y < m
queue = deque([(0, 0, 1)]) # (x, y, distance)
visited = set((0, 0))
while queue... | def test_shortest_path_no_obstacles():
grid = [
[1, 1, 1],
[1, 1, 1],
[1, 1, 1]
]
assert find_shortest_path(3, 3, grid) == 5
def test_shortest_path_with_obstacles():
grid = [
[1, 0, 1, 1],
[1, 1, 0, 1],
[0, 1, 0, 1],
[1, 1, 1, 1]
]
assert ... | [
{
"docstring": null,
"function_declaration": "def shortest_path_in_grid(grid):",
"function_name": "shortest_path_in_grid",
"parameter_list": "(grid)"
},
{
"docstring": null,
"function_declaration": "def find_shortest_path(n, m, grid):",
"function_name": "find_shortest_path",
"par... | [
0,
1,
0,
0,
1,
0,
0,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import deque\n\ndef shortest_path(grid):\n def bfs(start, end):\n n, m = len(grid), len(grid[0])\n queue = deque([start])\n ... | trial_gpt4o_1 | {
"original_instruction": "You are given a city grid and it's represented as a 2D array. Each cell in the 2D array represents a city block. The value of the cell can either be `0` (representing an obstacle) or `1` (representing an accessible path). A person can move from one block to any of the four side-adjacent blo... | 0.730231 | Codeforces_7447 | C | [
"shortest_path_in_grid",
"find_shortest_path"
] | 2 | [
[
"find_shortest_path",
"shortest_path_in_grid"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 6e70e769e5144a782df07fe828a07646f261babf | 8a82e7e035387a9ce94bfacb06cc975ce07af197 | |||
v1.0 | complete | Codeforces | Codeforces_7130_C | class TreeNode:
def __init__(self, key):
self.left = None
self.right = None
self.val = key
def insert(root, key):
"""Function to insert a new node with the given key in the BST."""
# Implementation goes here
def find_predecessor_successor(root, key):
"""
Function to find th... | class TreeNode:
def __init__(self, key):
self.left = None
self.right = None
self.val = key
def insert(root, key):
"""Function to insert a new node with the given key in the BST."""
if root is None:
return TreeNode(key)
if key < root.val:
root.left = insert(root.l... | from solution import bst_predecessor_successor_repr
def test_example_case():
n = 5
values = [20, 10, 30, 5, 15]
assert bst_predecessor_successor_repr(n, values) == [
"-1 -1",
"-1 20",
"20 -1",
"-1 10",
"10 20"
]
def test_all_increasing():
n = 4
values = ... | [] | [
1,
1,
0,
0,
0,
0,
0,
0,
1,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, key):\n self.left = None\n self.right = None\n self.val = key\n\ndef insert(root, key):\n \"\"... | trial_gpt4o_0 | {
"original_instruction": "Polycarp is learning about binary search trees (BST) and their properties. He has recently come across the concept of the in-order traversal of a BST, which returns the elements of the tree in sorted order. However, Polycarp is more interested in the properties of nodes in the BST relative ... | 0.53357 | Codeforces_7130 | C | [
"insert",
"find_predecessor_successor",
"bst_insertion_with_predecessor_successor",
"bst_predecessor_successor_repr"
] | 4 | [
[
"bst_insertion_with_predecessor_successor",
"find_predecessor_successor"
],
[
"bst_insertion_with_predecessor_successor",
"insert"
],
[
"bst_predecessor_successor_repr",
"bst_insertion_with_predecessor_successor"
]
] | 3 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | c4fcd603cfa16f1bc11ddb260ea5f23cd7517553 | d4dfa33335f18e53815caaf58dce06e827abe1a8 | |||
v1.0 | complete | Codeforces | Codeforces_7467_C | class TreeNode:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def insert_into_bst(root, value):
if root is None:
return TreeNode(value)
if value < root.value:
root.left = insert_into_bst(root.left, value)
elif value > root.value... | class TreeNode:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def insert_into_bst(root, value):
if root is None:
return TreeNode(value)
if value < root.value:
root.left = insert_into_bst(root.left, value)
elif value > root.value... | from solution import bst_from_sequence
def test_bst_valid_sequence():
assert bst_from_sequence("5 3 7 2 4 6 8") == [5, 3, 7, 2, 4, 6, 8]
def test_bst_with_duplicates():
assert bst_from_sequence("5 3 3 2 4 6 8") == -1
def test_bst_single_element():
assert bst_from_sequence("10") == [10]
def test_bst_empt... | [] | [
0,
1,
1,
1,
1,
1,
1,
1,
0,
0
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, value):\n self.value = value\n self.left = None\n self.right = None\n\ndef insert_into_bst(root, ... | trial_gpt4o_7 | {
"original_instruction": "Given a sequence of integers, arrange them into a binary search tree (BST). A BST is a binary tree in which for each node, the values in its left subtree are less than the node's value, and the values in its right subtree are greater than the node's value.\n\nWrite a function to build and p... | 0.55778 | Codeforces_7467 | C | [
"insert_into_bst",
"build_bst",
"level_order_traversal",
"bst_from_sequence"
] | 4 | [
[
"bst_from_sequence",
"build_bst"
],
[
"bst_from_sequence",
"level_order_traversal"
],
[
"build_bst",
"insert_into_bst"
]
] | 3 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 0d27e55767d6538c2e2bce0f0742c048947da8ca | 21967d7ebfa4825c3757d6a403c89fd7a98020d3 | |||
v1.0 | complete | Codeforces | Codeforces_8454_C | from typing import Tuple, Union
def find_two_primes_sum(n: int) -> Union[Tuple[str], Tuple[str, int, int]]:
"""
Determines if n can be represented as the sum of exactly two distinct positive integers that are both prime.
If possible, return a tuple ("YES", p1, p2). Otherwise, return ("NO",).
>>> find_t... | def is_prime(num):
"""Helper function to check if a number is prime"""
if num <= 1:
return False
if num <= 3:
return True
if num % 2 == 0 or num % 3 == 0:
return False
i = 5
while i * i <= num:
if num % i == 0 or num % (i + 2) == 0:
return False
... | from solution import find_two_primes_sum
def test_find_two_primes_sum_example_1():
assert find_two_primes_sum(10) == ("YES", 3, 7) or find_two_primes_sum(10) == ("YES", 5, 5)
def test_find_two_primes_sum_example_2():
assert find_two_primes_sum(11) == ("NO",)
def test_find_two_primes_sum_small_numbers():
... | [
{
"docstring": "Helper function to check if a number is prime",
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "Determines if n can be represented as the sum of exactly two distinct positive integers that are both prime.... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(num):\n if num <= 1:\n return False\n if num <= 3:\n return True\n if num % 2 == 0 or num % 3 == 0:\n return False\... | trial_gpt4o_9 | {
"original_instruction": "Given an integer `n` (1 ≤ n ≤ 10^9), determine if you can represent it as the sum of exactly two distinct positive integers such that both integers are prime. If it is possible, print \"YES\" and the two integers. Otherwise, print \"NO\".\n\nFor example:\n1. Input: 10\n Output: YES\n ... | 0.678295 | Codeforces_8454 | C | [
"is_prime",
"find_two_primes_sum"
] | 2 | [
[
"find_two_primes_sum",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7159053b9e79c4147ff89e44c17798a11d618cfc | 9d2f016a3ab42bfd869cab73a5270d3e5085de1d | |||
v1.0 | complete | Codeforces | Codeforces_8548_C | from typing import List
def max_notification_time(intervals: List[int]) -> int:
""" Given an array of integers where each integer represents the preferred notification interval
(in minutes) for each team member, returns the least common multiple of the intervals,
representing the maximum time it would ta... | from math import gcd
from functools import reduce
from typing import List
def lcm(a, b):
"""
Helper function to calculate the least common multiple of two numbers.
"""
return abs(a * b) // gcd(a, b)
def max_notification_time(intervals: List[int]) -> int:
"""
Given an array of integers where ea... | from solution import max_notification_time
def test_example_cases():
assert max_notification_time([5, 10, 15]) == 30
assert max_notification_time([1, 2, 3]) == 6
assert max_notification_time([7, 5, 6]) == 210
def test_single_interval():
assert max_notification_time([5]) == 5
assert max_notificatio... | [
{
"docstring": "Helper function to calculate the least common multiple of two numbers.",
"function_declaration": "def lcm(a, b):",
"function_name": "lcm",
"parameter_list": "(a, b)"
},
{
"docstring": "Given an array of integers where each integer represents the preferred notification interva... | [
1,
1,
1,
1,
0,
1,
0,
1,
0,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\nfrom functools import reduce\nfrom typing import List\n\ndef lcm(a: int, b: int) -> int:\n return abs(a*b) // math.gcd(a, b)\n\ndef max_notifi... | trial_gpt4o_9 | {
"original_instruction": "A company has a team of software engineers who often collaborate on different projects. They usually communicate via a group chat, and each team member has unique preferences for how they like to be notified about new messages. Some prefer instant notifications, while others check messages ... | 0.605043 | Codeforces_8548 | C | [
"lcm",
"max_notification_time"
] | 2 | [
[
"max_notification_time",
"lcm"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 26a44aa97ae6fa49afaf641892d31491cbbe3702 | 67b1815b14a5af716919af77a9897e482b543d5f | |||
v1.0 | complete | Codeforces | Codeforces_7383_C | from typing import List, Tuple
def edmonds_karp(n: int, edges: List[Tuple[int, int, int]]) -> int:
""" Computes the maximum flow from source (location 1) to sink (location n).
Args:
n (int): The number of locations.
edges (List[Tuple[int, int, int]]): List of triples representing the roads where each ... | from collections import deque
def bfs(capacity, source, sink, parent):
"""
Returns true if there is a path from source to sink in residual graph.
Also fills parent to store the path.
"""
visited = [False] * len(capacity)
queue = deque([source])
visited[source] = True
while queue:
... | def test_small_graph():
n = 4
m = 5
edges = [
(1, 2, 40),
(1, 3, 20),
(2, 3, 10),
(2, 4, 30),
(3, 4, 20)
]
assert edmonds_karp(n, edges) == 50
def test_single_path():
n = 4
m = 3
edges = [
(1, 2, 10),
(2, 3, 5),
(3, 4, 10)
... | [
{
"docstring": "Returns true if there is a path from source to sink in residual graph.\nAlso fills parent to store the path.",
"function_declaration": "def bfs(capacity, source, sink, parent):",
"function_name": "bfs",
"parameter_list": "(capacity, source, sink, parent)"
},
{
"docstring": "R... | [
0,
0,
0,
0,
0,
1,
0,
0,
0,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import deque, defaultdict\n\ndef bfs_capacity(graph, source, sink, parent):\n visited = set()\n queue = deque([source])\n visited.ad... | trial_gpt4o_9 | {
"original_instruction": "A city has a network of roads connecting various locations. Each road has a specific traffic capacity representing the maximum number of vehicles that can pass through it per unit time. Your task is to determine the maximum number of vehicles that can travel from a starting location (source... | 0.64667 | Codeforces_7383 | C | [
"bfs",
"edmonds_karp"
] | 2 | [
[
"edmonds_karp",
"bfs"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 424c86779854d3534bf987f4ea857810a77bedcb | 91ea385210164cdac16a22a6f0d52a9aeb87b0ae | |||
v1.0 | complete | Codeforces | Codeforces_7209_C | def parse_and_solve(m: int, x: int, coin_data: List[Tuple[int, int]]) -> Tuple[int, List[int]]:
"""
Given the denominations and counts of each coin type, finds the maximum
possible sum of denominations that can be achieved with exactly x coins
in a row, along with the indices of the selected coin type... | def max_sum_denominations(m, x, coin_info):
"""
Returns the maximum sum of denominations and the indices of coins
that produce this sum given m types of coins and a row length of x.
Parameters:
m (int): The number of different types of coins
x (int): The number of coins Alex wants ... | from solution import parse_and_solve
def test_basic_case():
m = 5
x = 3
coins = [(5, 3), (2, 1), (7, 2), (4, 5), (6, 2)]
max_sum, indices = parse_and_solve(m, x, coins)
assert max_sum == 18
assert sorted(indices) == sorted([3, 5, 1])
def test_all_same_denomination():
m = 5
x = 3
c... | [
{
"docstring": "Returns the maximum sum of denominations and the indices of coins \nthat produce this sum given m types of coins and a row length of x.\n\nParameters:\n m (int): The number of different types of coins\n x (int): The number of coins Alex wants to place in a single row\n coin_info (list o... | [
1,
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def max_sum_of_denominations(m, x, denominations_counts):\n # sort the denominations and their indices in descending order based on the denomination values... | trial_gpt4o_9 | {
"original_instruction": "Alex has a passion for collecting coins of various denominations. He recently obtained a collection of coins and wants to organize them in a special way. Alex has m different types of coins, where each type i is characterized by its denomination di and the count of coins ci.\n\nAlex desires... | 0.645388 | Codeforces_7209 | C | [
"max_sum_denominations",
"parse_and_solve"
] | 2 | [
[
"parse_and_solve",
"max_sum_denominations"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 84229f38f9e5773d0925b13ed0402fffaa595e3e | 1ea9160004aa169d9d872b9f7e09b6abbd82702b | |||
v1.0 | complete | Codeforces | Codeforces_8410_C | from typing import List
def calculate_combinations(n: int, m: int, k: int, card_values: List[int], remaining_values: List[int]) -> int:
"""
Calculate the total possible combinations of the remaining cards that would keep the sum V intact.
Args:
n: Number of players
m: Number of cards each player h... | from collections import Counter
from math import comb
def calculate_combinations(n, m, k, card_values, remaining_values):
"""
Calculate possible combinations of remaining cards to maintain a sum V.
Args:
n (int): Number of players
m (int): Number of cards each player has drawn
k (in... | from solution import calculate_combinations
def test_example_case():
assert calculate_combinations(2, 3, 3, [1, 2, 3], [1, 2, 2, 3, 3]) == 1
def test_all_cards_present():
assert calculate_combinations(1, 3, 1, [100], [100, 100, 100]) == 1
def test_some_missing_cards():
assert calculate_combinations(1, 3,... | [
{
"docstring": "Calculate possible combinations of remaining cards to maintain a sum V.\nArgs:\n n (int): Number of players\n m (int): Number of cards each player has drawn\n k (int): Number of unique card values\n card_values (list): List of k card values\n remaining_values (list): List of remai... | [
0,
0,
1,
0,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import Counter\n\ndef calculate_possible_combinations(n, m, k, card_values, remaining_cards):\n \"\"\"\n Calculates the number of possi... | trial_gpt4o_2 | {
"original_instruction": "Polycarp is organizing a card tournament. There are n players and each player has m randomly drawn cards from a deck containing cards with values c1, c2, ..., ck (0 ≤ ci ≤ 106). Each card value appears equally often in the deck. Polycarp wants to calculate the total sum of all card values f... | 0.6563 | Codeforces_8410 | C | [
"calculate_combinations",
"calculate_combinations_recursively"
] | 2 | [
[
"calculate_combinations",
"calculate_combinations_recursively"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d3328c675e4849cf49466952765b889a5664924e | 8a5aca2050ee78be74baba0608e0e31d6caa8fe6 | |||
v1.0 | complete | Codeforces | Codeforces_7840_C | def find_minimal_path(n: int, m: int, roads: List[Tuple[int, int]]) -> List[int]:
"""Find the three cities and the order in which the traveler should visit them to minimize the total travel distance.
Args:
n (int): The number of cities.
m (int): The number of one-way roads.
roads (List[... | import sys
import heapq
from collections import defaultdict
def floyd_warshall(n, graph):
dist = [[sys.maxsize] * n for _ in range(n)]
for i in range(n):
dist[i][i] = 0
for u in range(n):
for v in graph[u]:
dist[u][v] = 1
for k in range(n):
for i in ra... | from solution import find_minimal_path
def test_example_scenario_1():
n = 5
m = 6
roads = [
(1, 2),
(2, 3),
(3, 4),
(4, 5),
(1, 3),
(2, 4)
]
result = find_minimal_path(n, m, roads)
assert result == [1, 2, 3] or result == [2, 3, 4]
def test_minima... | [
{
"docstring": null,
"function_declaration": "def floyd_warshall(n, graph):",
"function_name": "floyd_warshall",
"parameter_list": "(n, graph)"
},
{
"docstring": null,
"function_declaration": "def minimize_travel_distance(n, m, roads):",
"function_name": "minimize_travel_distance",
... | [
1,
1,
1,
0,
1,
1,
1,
0,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import heapq\n\ndef find_shortest_paths(n, roads):\n # Initialize graph\n graph = [[] for _ in range(n + 1)]\n \n for u, v in roads:\n grap... | trial_gpt4o_9 | {
"original_instruction": "A traveler wants to explore a certain country. The country has n cities and m one-way roads connecting them. The traveler wants to visit exactly three distinct cities in such a way that the total distance traveled is minimized. The traveler can start from any city and end in any city but mu... | 0.683397 | Codeforces_7840 | C | [
"floyd_warshall",
"minimize_travel_distance",
"find_minimal_path"
] | 3 | [
[
"find_minimal_path",
"minimize_travel_distance"
],
[
"minimize_travel_distance",
"floyd_warshall"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | af61ce2102a72b23156374b1e25a28b3bfbee418 | be468d0d41e7e637aa217143f4145545ef35a03c | |||
v1.0 | complete | Codeforces | Codeforces_10174_C | def generate_summary(log_entries, server_id):
"""
Processes log entries and generates a summary report for a specified server_id.
:param log_entries: List of log entry strings.
:param server_id: Integer representing the server_id for which the summary report is to be generated.
:return: String form... | def process_log_entries(log_entries, server_id):
"""
Processes log entries and generates a summary report for a specified server_id.
:param log_entries: List of log entry strings.
:param server_id: Integer representing the server_id for which the summary report is to be generated.
:return: Dict... | from solution import generate_summary
def test_generate_summary():
log_entries = [
"2023-01-01 12:00:00 1 ERROR Disk full",
"2023-01-01 12:05:00 2 INFO Service started",
"2023-01-01 12:10:00 1 WARNING CPU load high",
"2023-01-01 12:15:00 1 INFO Service started",
"2023-01-01 ... | [
{
"docstring": "Processes log entries and generates a summary report for a specified server_id.\n\n:param log_entries: List of log entry strings.\n:param server_id: Integer representing the server_id for which the summary report is to be generated.\n:return: Dictionary with the count and last timestamp of each ... | [
0,
0,
0,
1,
0,
0,
1,
0,
1,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def process_logs(log_entries, target_server_id):\n \"\"\"\n Processes log entries and generates a summary report for the given server_id.\n \n Arg... | trial_gpt4o_8 | {
"original_instruction": "You are given a collection of events log data from various servers in a distributed system. Each log entry is a single line in the format \"timestamp server_id event_type description\". The description can be any string and can include spaces, while the timestamp is in \"YYYY-MM-DD hh:mm:ss... | 0.656911 | Codeforces_10174 | C | [
"process_log_entries",
"format_summary",
"generate_summary"
] | 3 | [
[
"generate_summary",
"format_summary"
],
[
"generate_summary",
"process_log_entries"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 68d4ba2f493197b0636f01d252133284a48f54a7 | d9f01080b0ed99f74ffd5b4e16013e097f7e6e71 | |||
v1.0 | complete | Codeforces | Codeforces_8523_C | def largest_square_submatrix_area(n: int, m: int, matrix: List[List[int]]) -> int:
"""
Given a binary matrix, finds the area of the largest square
sub-matrix consisting entirely of 1's. Returns the area of that
square sub-matrix.
>>> matrix = [
... [1, 0, 1, 0, 0, 1],
... [1, 0, 1, ... | def maximalSquare(matrix):
"""
Given a binary matrix, finds the area of the largest square
sub-matrix consisting entirely of 1's.
"""
if not matrix or not matrix[0]:
return 0
n = len(matrix)
m = len(matrix[0])
dp = [[0] * m for _ in range(n)]
max_side = 0
for i in r... | import pytest
from solution import largest_square_submatrix_area
def test_largest_square_submatrix_area_example():
matrix = [
[1, 0, 1, 0, 0, 1],
[1, 0, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1],
[1, 0, 0, 1, 1, 1],
[1, 1, 1, 1, 1, 1]
]
assert largest_square_submatrix_area(5, ... | [
{
"docstring": "Given a binary matrix, finds the area of the largest square\nsub-matrix consisting entirely of 1's.",
"function_declaration": "def maximalSquare(matrix):",
"function_name": "maximalSquare",
"parameter_list": "(matrix)"
},
{
"docstring": null,
"function_declaration": "def ... | [
0,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def largest_square_area(matrix):\n \"\"\"\n Returns the area of the largest square sub-matrix filled with 1's.\n \"\"\"\n n = len(matrix)\n m =... | trial_gpt4o_3 | {
"original_instruction": "You are given a binary matrix where each cell can either be 0 or 1. The task is to find the largest square sub-matrix consisting entirely of 1's and return its area.\n\nThe input consists of:\n- An integer n (1 ≤ n ≤ 1000), the number of rows in the matrix.\n- An integer m (1 ≤ m ≤ 1000), t... | 0.658679 | Codeforces_8523 | C | [
"maximalSquare",
"largest_square_submatrix_area"
] | 2 | [
[
"largest_square_submatrix_area",
"maximalSquare"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8bed0a0b5296dd03c8a1aee6a8008544ea7b984c | 685dd7d40c6aaebd5d42ab3afbe39a7aa7f93199 | |||
v1.0 | complete | Codeforces | Codeforces_9268_C | def maximalRectangle(matrix: List[List[int]]) -> int:
""" Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle (containing only 1's) and return its area.
>>> maximalRectangle([[1, 0, 1, 0, 0], [1, 0, 1, 1, 1], [1, 1, 1, 1, 1], [1, 0, 0, 1, 0]]) == 6
>>> maximalRectangle([[0, 1],... | def maximalRectangle(matrix):
if not matrix:
return 0
max_area = 0
dp = [0] * len(matrix[0])
for row in matrix:
for i in range(len(row)):
dp[i] = dp[i] + 1 if row[i] == 1 else 0
max_area = max(max_area, largestRectangleArea(dp))
return max_... | def test_maximalRectangle():
matrix1 = [
[1, 0, 1, 0, 0],
[1, 0, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 0, 0, 1, 0]
]
assert maximalRectangle(matrix1) == 6
matrix2 = [
[0, 1],
[1, 0]
]
assert maximalRectangle(matrix2) == 1
matrix3 = [
... | [
{
"docstring": null,
"function_declaration": "def maximalRectangle(matrix):",
"function_name": "maximalRectangle",
"parameter_list": "(matrix)"
},
{
"docstring": null,
"function_declaration": "def largestRectangleArea(heights):",
"function_name": "largestRectangleArea",
"paramete... | [
0,
0,
0,
0,
1,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def maximalRectangle(m, n, matrix):\n def maximal_histogram_area(heights):\n stack = []\n max_area = 0\n index = 0\n \n ... | trial_gpt4o_4 | {
"original_instruction": "Maximal Rectangle in a Grid\n\nGiven a 2D binary matrix filled with 0’s and 1’s, find the largest rectangle (containing only 1’s) and return its area.\n\n### Input Format\nThe input consists of two lines:\n- The first line contains two integers $$$ m $$$ and $$$ n $$$ ($$$1 \\le m, n \\le 2... | 0.722919 | Codeforces_9268 | C | [
"maximalRectangle",
"largestRectangleArea",
"read_input"
] | 3 | [
[
"maximalRectangle",
"largestRectangleArea"
]
] | 1 | [
"read_input"
] | false | [] | false | pytest | false | [] | true | 3ca488871e79da7a26d8530c4b0705190b65d473 | a3979c5fab90325d4b36f81d6346cd587ddc50fc | |||
v1.0 | complete | Codeforces | Codeforces_10979_C | def is_uniform_path(grid: List[str]) -> str:
""" Determine if there exists a path from the top-left corner to the bottom-right corner
in a grid such that all cells in the path contain the same letter.
You can only move right or down from a cell.
>>> is_uniform_path([
"aaaa",
"abaa"... | def is_uniform_path(grid):
n = len(grid)
m = len(grid[0])
target_char = grid[0][0]
# DP table for marking reachable cells with the same character
dp = [[False] * m for _ in range(n)]
dp[0][0] = True
for i in range(n):
for j in range(m):
if dp[i][j] and grid[i][j... | from solution import is_uniform_path
def test_example_1():
grid = [
"aaaa",
"abaa",
"aaaa"
]
assert is_uniform_path(grid) == "YES"
def test_example_2():
grid = [
"ab",
"bb"
]
assert is_uniform_path(grid) == "NO"
def test_example_3():
grid = [
... | [
{
"docstring": null,
"function_declaration": "def is_uniform_path(grid):",
"function_name": "is_uniform_path",
"parameter_list": "(grid)"
},
{
"docstring": null,
"function_declaration": "def uniform_path(grid):",
"function_name": "uniform_path",
"parameter_list": "(grid)"
}
] | [
0,
1,
0,
0,
1,
0,
0,
1,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def find_path(n, m, grid):\n visited = [[False for _ in range(m)] for _ in range(n)]\n target_letter = grid[0][0]\n\n def dfs(x, y):\n if x >=... | trial_gpt4o_4 | {
"original_instruction": "**Problem Statement**\n\nYou are given a 2D grid of size `n x m` with each cell containing a lowercase English letter. Your task is to determine if there exists a path from the top-left corner (cell (1,1)) to the bottom-right corner (cell (n,m)) such that all cells in the path contain the s... | 0.637677 | Codeforces_10979 | C | [
"is_uniform_path",
"uniform_path"
] | 2 | [
[
"uniform_path",
"is_uniform_path"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8c8fc5cce4e7f2f644ab24098df63b797b21aaa8 | f52b477c2a6a38386a14681f3ca74a62b83884fa | |||
v1.0 | complete | Codeforces | Codeforces_7676_C | from typing import List, Tuple
def flip_submatrix(matrix: List[List[str]], r1: int, c1: int, r2: int, c2: int) -> None:
""" Flip the elements of the submatrix defined by top-left (r1, c1) and bottom-right (r2, c2) corners. """
for i in range(r1, r2 + 1):
for j in range(c1, c2 + 1):
matrix[i... | def flip_submatrix(matrix, r1, c1, r2, c2):
for i in range(r1, r2 + 1):
for j in range(c1, c2 + 1):
matrix[i][j] = '1' if matrix[i][j] == '0' else '0'
def is_uniform(matrix):
first_value = matrix[0][0]
for row in matrix:
for value in row:
if value != first_value:
... | from solution import min_operations_to_uniform, read_matrix_input
def test_uniform_matrix():
input_str = """2 2
00
00"""
matrix = read_matrix_input(input_str)
num_operations, operations = min_operations_to_uniform(matrix)
assert num_operations == 0
assert operations == []
def test_non_unif... | [
{
"docstring": null,
"function_declaration": "def flip_submatrix(matrix, r1, c1, r2, c2):",
"function_name": "flip_submatrix",
"parameter_list": "(matrix, r1, c1, r2, c2)"
},
{
"docstring": null,
"function_declaration": "def is_uniform(matrix):",
"function_name": "is_uniform",
"p... | [
0,
0,
0,
1,
0,
0,
0,
0,
0,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def min_operations_to_uniform_matrix(matrix):\n n = len(matrix)\n m = len(matrix[0])\n \n # Helper function to flip the submatrix\n def flip_su... | trial_gpt4o_9 | {
"original_instruction": "You are given a binary matrix of size $$$n \\times m$$$. The goal is to make all elements of the matrix equal using the minimum number of operations. In one operation, you can select a rectangular submatrix and flip all of its elements (change 0 to 1 and 1 to 0).\n\nDetermine the minimum nu... | 0.622216 | Codeforces_7676 | C | [
"flip_submatrix",
"is_uniform",
"min_operations_to_uniform",
"read_matrix_input"
] | 4 | [
[
"min_operations_to_uniform",
"flip_submatrix"
],
[
"min_operations_to_uniform",
"is_uniform"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 8175c410bac2b0137d61d5e856e9d7f1ffd779d4 | b3327e950fcb5208cc5d5d11dba0fb24f9cb917b | |||
v1.0 | complete | Codeforces | Codeforces_11402_C | def sum_of_digits(n: int) -> int:
"""
Returns the sum of the digits of a number n.
"""
pass
def distinct_terms_count(x: int, k: int) -> int:
"""
Returns the number of distinct terms in the sequence after k iterations starting with x.
>>> distinct_terms_count(1, 1)
2
>>> distinc... | def sum_of_digits(n):
"""
Returns the sum of the digits of a number n.
"""
return sum(int(digit) for digit in str(n))
def distinct_terms_count(x, k):
"""
Returns the number of distinct terms in the sequence after k iterations starting with x.
"""
sequence = set()
current_term = x
... | from solution import distinct_terms_count
def test_small_numbers():
assert distinct_terms_count(1, 1) == 2
assert distinct_terms_count(2, 2) == 3
def test_larger_number():
assert distinct_terms_count(13, 2) == 3 # Sequence: 13, 139, 1391
def test_large_k():
assert distinct_terms_count(9, 10) == 11
... | [
{
"docstring": "Returns the sum of the digits of a number n.",
"function_declaration": "def sum_of_digits(n):",
"function_name": "sum_of_digits",
"parameter_list": "(n)"
},
{
"docstring": "Returns the number of distinct terms in the sequence after k iterations starting with x.",
"functio... | [
1,
0,
1,
0,
1,
1,
0,
0,
1,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def digit_sum(n):\n \"\"\"\n Returns the sum of the digits of a number n.\n \"\"\"\n return sum(map(int, str(n)))\n\ndef count_distinct_terms(x, k... | trial_gpt4o_9 | {
"original_instruction": "Valera likes to play with numbers. One day, he found an interesting sequence and wants to know more about it. The sequence is constructed as follows:\n\n- It starts with a positive integer x.\n- For each next term in the sequence, Valera adds up the digits of the current term and appends th... | 0.610006 | Codeforces_11402 | C | [
"sum_of_digits",
"distinct_terms_count"
] | 2 | [
[
"distinct_terms_count",
"sum_of_digits"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 463bf233455f15c00dada5e1f952ba811b4d8994 | 0a533d2229540da4a1ed618aa8cf853b0dbed4c0 | |||
v1.0 | complete | Codeforces | Codeforces_8608_C | def preprocess_matrix(matrix):
"""
Preprocess the matrix to create an auxiliary sum_matrix where sum_matrix[i][j]
contains the sum of elements from (0,0) to (i-1, j-1) in the original matrix.
"""
pass
def submatrix_sum(sum_matrix, x1, y1, x2, y2):
"""
Calculate the sum of elements in the su... | def preprocess_matrix(matrix):
"""
Preprocess the matrix to create an auxiliary sum_matrix where sum_matrix[i][j]
contains the sum of elements from (0,0) to (i-1, j-1) in the original matrix.
"""
n = len(matrix)
m = len(matrix[0])
sum_matrix = [[0] * (m + 1) for _ in range(n + 1)]
... | from solution import preprocess_matrix, submatrix_sum, matrix_query_sums
def test_preprocess_matrix():
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
expected = [
[0, 0, 0, 0],
[0, 1, 3, 6],
[0, 5, 12, 21],
[0, 12, 27, 45]
]
assert preproces... | [
{
"docstring": "Preprocess the matrix to create an auxiliary sum_matrix where sum_matrix[i][j]\ncontains the sum of elements from (0,0) to (i-1, j-1) in the original matrix.",
"function_declaration": "def preprocess_matrix(matrix):",
"function_name": "preprocess_matrix",
"parameter_list": "(matrix)"... | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def matrix_sum_submatrix(n, m, matrix, queries):\n # Precomputing prefix sums\n prefix_sum = [[0] * (m + 1) for _ in range(n + 1)]\n \n for i in r... | trial_gpt4o_6 | {
"original_instruction": "A matrix is a rectangular array of numbers arranged in rows and columns. You are given a matrix of size $$$n \\times m$$$ and you need to answer $$$q$$$ queries.\n\nEach query is defined by four integers $$$x_1, y_1, x_2, y_2$$$ which describe the top-left and bottom-right corners of a subm... | 0.568966 | Codeforces_8608 | C | [
"preprocess_matrix",
"submatrix_sum",
"matrix_query_sums"
] | 3 | [
[
"matrix_query_sums",
"preprocess_matrix"
],
[
"matrix_query_sums",
"submatrix_sum"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | e2f9a350da92a1a3677a9dbae530cadac0f0c91d | 6ea2762d8761976e68732dc3fcc47db9f5df5ca0 | |||
v1.0 | complete | Codeforces | Codeforces_12052_C | def has_sequential_identical_digits(n):
"""Helper function to check if a number has sequential identical digits."""
num_str = str(n)
for i in range(len(num_str) - 1):
if num_str[i] == num_str[i+1]:
return True
return False
def generate_sequence(k):
"""
Generate the first k n... | def has_sequential_identical_digits(n):
"""Helper function to check if a number has sequential identical digits."""
num_str = str(n)
for i in range(len(num_str) - 1):
if num_str[i] == num_str[i+1]:
return True
return False
def generate_sequence(k):
"""
Generate the first k n... | from solution import generate_sequence, has_sequential_identical_digits
def test_has_sequential_identical_digits():
assert has_sequential_identical_digits(112) == True
assert has_sequential_identical_digits(121) == False
assert has_sequential_identical_digits(333) == True
assert has_sequential_identica... | [
{
"docstring": "Helper function to check if a number has sequential identical digits.",
"function_declaration": "def has_sequential_identical_digits(n):",
"function_name": "has_sequential_identical_digits",
"parameter_list": "(n)"
},
{
"docstring": "Generate the first k numbers less than 100... | [
1,
0,
1,
1,
1,
1,
0,
0,
1
] | 6 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def generate_sequence(k):\n \"\"\"\n Generates the first k numbers where every number is less than 1000 and devoid of \n any sequential identical dig... | trial_gpt4o_8 | {
"original_instruction": "A dedicated mathematician named Alice is fascinated by sequences and patterns. She came across a problem where she needs to find a sequence of numbers that meet a specific criterion.\n\nFor a given positive integer k, she needs to generate the first k numbers in a sequence where every numbe... | 0.66038 | Codeforces_12052 | C | [
"has_sequential_identical_digits",
"generate_sequence"
] | 2 | [
[
"generate_sequence",
"has_sequential_identical_digits"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f386bab1ce9829b1f061a8b572c9d4e904e81c04 | abd708ec51891ae72126c883205c372921095f2e | |||
v1.0 | complete | Codeforces | Codeforces_10219_C | def can_be_nearly_sorted(n: int, a: List[int]) -> str:
"""
Determine whether it is possible to make the array "Nearly Sorted" by swapping
exactly one pair of adjacent elements.
Parameters:
n (int): Length of the array
a (list): List of integers representing the array a
Returns:
str: 'Y... | def can_be_nearly_sorted(n, a):
"""
Determine whether it is possible to make the array "Nearly Sorted" by swapping
exactly one pair of adjacent elements.
Parameters:
n (int): Length of the array
a (list): List of integers representing the array a
Returns:
str: 'YES' if it is po... | def test_can_be_nearly_sorted_case1():
assert can_be_nearly_sorted(4, [2, 3, 1, 4]) == 'YES'
def test_can_be_nearly_sorted_case2():
assert can_be_nearly_sorted(5, [1, 5, 3, 4, 2]) == 'NO'
def test_can_be_nearly_sorted_case3():
assert can_be_nearly_sorted(5, [1, 2, 3, 5, 4]) == 'YES'
def test_can_be_nearl... | [
{
"docstring": "Determine whether it is possible to make the array \"Nearly Sorted\" by swapping\nexactly one pair of adjacent elements.\n\nParameters:\nn (int): Length of the array\na (list): List of integers representing the array a\n\nReturns:\nstr: 'YES' if it is possible, 'NO' otherwise",
"function_dec... | [
1,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def can_be_nearly_sorted(n, a):\n \"\"\"\n Determine whether it is possible to make the array \"Nearly Sorted\" by swapping\n exactly one pair of adj... | trial_gpt4o_0 | {
"original_instruction": "You are given an array of integers $$$a$$$. Your goal is to perform exactly one operation on the array to make it \"Nearly Sorted\". An array is considered \"Nearly Sorted\" if each element is either in its correct position, or can be moved to its correct position in exactly one swap.\n\nYo... | 0.65829 | Codeforces_10219 | C | [
"can_be_nearly_sorted",
"is_nearly_sorted"
] | 2 | [
[
"can_be_nearly_sorted",
"is_nearly_sorted"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | f0ead5da71456e73b8dd08c81540405a756ec696 | 930af24d4c7ca8da435ef8e30b651bf3a216130d | |||
v1.0 | complete | Codeforces | Codeforces_10969_C | def number_of_ways(n: int, m: int, grid: List[str]) -> int:
""" Returns the number of ways to reach the bottom-right corner of the grid
from the top-left corner without passing through any obstacles.
Parameters:
n (int): number of rows in the grid
m (int): number of columns in the grid
grid (Li... | def count_paths(grid, n, m):
"""
Returns the number of ways to reach the bottom-right corner
from the top-left corner without passing through any obstacles.
"""
# Initialize dp table with 0s
dp = [[0] * m for _ in range(n)]
# Start position is (0, 0), initialize accordingly
if grid[... | from solution import number_of_ways
def test_example1():
n, m = 3, 3
grid = [
"...",
".#.",
"..."
]
assert number_of_ways(n, m, grid) == 2
def test_example2():
n, m = 3, 3
grid = [
".#.",
".#.",
"..."
]
assert number_of_ways(n, m, grid) =... | [
{
"docstring": "Returns the number of ways to reach the bottom-right corner\nfrom the top-left corner without passing through any obstacles.",
"function_declaration": "def count_paths(grid, n, m):",
"function_name": "count_paths",
"parameter_list": "(grid, n, m)"
},
{
"docstring": null,
... | [
1,
0,
1,
1,
1,
1,
1,
1,
0,
0
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def count_paths(grid, n, m):\n if grid[0][0] == '#' or grid[n-1][m-1] == '#':\n return 0\n \n dp = [[0]*m for _ in range(n)]\n dp[0][0] = 1... | trial_gpt4o_7 | {
"original_instruction": "You are given a grid of size $$$n \\times m$$$, where each cell in the grid contains either a '.', representing an empty space, or a '#', representing an obstacle.\n\nYou need to find the number of ways to walk from the top-left corner of the grid (1, 1) to the bottom-right corner (n, m) su... | 0.701113 | Codeforces_10969 | C | [
"count_paths",
"number_of_ways"
] | 2 | [
[
"number_of_ways",
"count_paths"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d51eeb5980d4d50aa856f3f24de3aff8b99ac759 | 11df5489671c9e431066003c6e69f58adc32f684 | |||
v1.0 | complete | Codeforces | Codeforces_11826_C | from typing import List
def min_spell_casts(start: str, target: str, scrolls: List[str]) -> int:
""" Returns the minimum number of spell casts needed to transform start into target
using the words in the scrolls. If it's not possible, returns -1.
>>> min_spell_casts("hit", "hot", ["hit", "dot", "dog",... | from collections import deque
def is_one_char_diff(word1, word2):
"""
Returns True if word1 and word2 differ by exactly one character.
"""
diff_count = 0
for c1, c2 in zip(word1, word2):
if c1 != c2:
diff_count += 1
if diff_count > 1:
return False
... | from solution import min_spell_casts
def test_example_case():
assert min_spell_casts("hit", "hot", ["hit", "dot", "dog", "lot", "log"]) == 1
def test_same_word():
assert min_spell_casts("abc", "abc", ["abc", "def", "ghi"]) == 0
def test_no_possible_transformation():
assert min_spell_casts("abc", "xyz", [... | [
{
"docstring": "Returns True if word1 and word2 differ by exactly one character.",
"function_declaration": "def is_one_char_diff(word1, word2):",
"function_name": "is_one_char_diff",
"parameter_list": "(word1, word2)"
},
{
"docstring": "Returns the minimum number of spell casts needed to tra... | [
1,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import deque\n\ndef is_one_char_diff(word1, word2):\n \"\"\"\n Returns True if word1 and word2 differ by exactly one character.\n \"... | trial_gpt4o_0 | {
"original_instruction": "In an ancient land, there is a magical library that consists of n scrolls arranged in a line. Each scroll contains a word, and some words are enchanted. A spell can be cast to transform one word into another only if they differ by exactly one character. Determining the minimum number of spe... | 0.510832 | Codeforces_11826 | C | [
"is_one_char_diff",
"min_spell_casts"
] | 2 | [
[
"min_spell_casts",
"is_one_char_diff"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 63a72e3f8bb96fbd215367a75b024a45a6b64c06 | 41fbfcbee0070afe1c726c24631900bbf462ab9a | |||
v1.0 | complete | Codeforces | Codeforces_10965_C | def find_two_distinct_paths(n: int, m: int, grid: List[str]) -> str:
""" Alice is playing a new game on a grid-like battlefield. The battlefield is represented by a grid of size n x m where each cell can either be empty (represented by '.') or contain an obstacle (represented by '#').
Alice starts at the top-l... | def find_paths(grid, n, m):
from collections import deque
def bfs(start_x, start_y):
queue = deque([(start_x, start_y)])
visited = [[False] * m for _ in range(n)]
parent = [[None] * m for _ in range(n)]
visited[start_x][start_y] = True
while queue:
... | from solution import find_two_distinct_paths
def test_example_case():
n, m = 4, 4
grid = [
"....",
".#..",
"..#.",
"...."
]
assert find_two_distinct_paths(n, m, grid) == "YES"
def test_no_paths():
n, m = 3, 3
grid = [
"###",
"#.#",
"###"
... | [
{
"docstring": null,
"function_declaration": "def find_paths(grid, n, m):",
"function_name": "find_paths",
"parameter_list": "(grid, n, m)"
},
{
"docstring": null,
"function_declaration": "def find_two_distinct_paths(n, m, grid):",
"function_name": "find_two_distinct_paths",
"par... | [
0,
0,
0,
0,
0,
0,
0,
1,
0
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import deque\n\ndef bfs(start, end, grid, n, m):\n directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]\n queue = deque([start])\n parent... | trial_gpt4o_8 | {
"original_instruction": "Alice is playing a new game on a grid-like battlefield. The battlefield is represented by a grid of size n x m where each cell can either be empty (represented by '.') or contain an obstacle (represented by '#').\n\nAlice starts at the top-left corner of the grid and wants to move to the bo... | 0.689545 | Codeforces_10965 | C | [
"find_paths",
"find_two_distinct_paths"
] | 2 | [
[
"find_two_distinct_paths",
"find_paths"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | bdd7766fc4e4de57a2839eb3c92e65458b2901c1 | ab5f5d548732950bfecf444fdbf8d9bc1a504b66 | |||
v1.0 | complete | Codeforces | Codeforces_11415_C | from collections import defaultdict
from typing import List, Tuple
def max_cities_visit(N: int, M: int, T: int, roads: List[Tuple[int, int, int]]) -> int:
""" Determine the maximum number of cities Aisha can visit within the given time limit T.
Args:
N (int): Number of cities.
M (int): Number of r... | from collections import defaultdict
def dfs(graph, node, visited, time_elapsed, T, count):
visited[node] = True
max_cities = count
for neighbor, travel_time in graph[node]:
if time_elapsed + travel_time <= T and not visited[neighbor]:
max_cities = max(max_cities, dfs(graph, neighbor, vi... | from solution import max_cities_visit
def test_example_case():
N = 5
M = 6
T = 7
roads = [
(1, 2, 2),
(1, 3, 4),
(2, 3, 1),
(2, 4, 5),
(3, 5, 3),
(4, 5, 2)
]
assert max_cities_visit(N, M, T, roads) == 4
def test_no_roads():
N = 3
M = 0
... | [
{
"docstring": null,
"function_declaration": "def dfs(graph, node, visited, time_elapsed, T, count):",
"function_name": "dfs",
"parameter_list": "(graph, node, visited, time_elapsed, T, count)"
},
{
"docstring": null,
"function_declaration": "def max_cities_visit(N, M, T, roads):",
"... | [
0,
0,
0,
1,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import heapq\n\ndef max_cities_within_time(N, M, T, roads):\n graph = [[] for _ in range(N + 1)]\n for u, v, t in roads:\n graph[u].append((v, t)... | trial_gpt4o_3 | {
"original_instruction": "Aisha is planning her vacation and is excited about visiting several cities. She has a map with N cities connected by M bidirectional roads with travel times. Aisha wants to visit as many cities as possible within a specified time limit T. She can start her journey from any city.\n\nHelp Ai... | 0.694495 | Codeforces_11415 | C | [
"dfs",
"max_cities_visit"
] | 2 | [
[
"max_cities_visit",
"dfs"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c358fce3840f36acd4df7668473655d4b4358f27 | 42c9a846ddacd6df6511b765c62ae8fada267303 | |||
v1.0 | complete | Codeforces | Codeforces_11583_C | from typing import List, Union, Tuple
def find_pair_with_prime_sum(n: int, lst: List[int]) -> Union[Tuple[int, int], str]:
""" You are given a sequence of integers. Your task is to find a pair of integers in the sequence such that their sum is a prime number. If there are multiple pairs, print the pair with the lo... | import itertools
def is_prime(num):
if num < 2:
return False
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
return False
return True
def find_pair_with_prime_sum(n, lst):
lst.sort()
pairs = list(itertools.combinations(lst, 2))
best_pair = None
for a, b ... | from solution import find_pair_with_prime_sum
def test_solution_example():
assert find_pair_with_prime_sum(5, [4, 7, 1, 10, 5]) == (1, 4)
def test_no_pairs():
assert find_pair_with_prime_sum(3, [4, 6, 8]) == "No pairs found"
def test_single_pair():
assert find_pair_with_prime_sum(2, [4, 3]) == (3, 4)
de... | [
{
"docstring": null,
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": null,
"function_declaration": "def find_pair_with_prime_sum(n, lst):",
"function_name": "find_pair_with_prime_sum",
"parameter_list": "(n, l... | [
0,
0,
0,
0,
0,
1,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(num):\n \"\"\"\n Checks if a number is prime.\n \"\"\"\n if num <= 1:\n return False\n if num == 2:\n return True\n ... | trial_gpt4o_5 | {
"original_instruction": "You are given a sequence of integers. Your task is to find a pair of integers in the sequence such that their sum is a prime number. If there are multiple pairs, print the pair with the lowest first element. If there are still ties, print the pair with the lowest second element. If there ar... | 0.749626 | Codeforces_11583 | C | [
"is_prime",
"find_pair_with_prime_sum"
] | 2 | [
[
"find_pair_with_prime_sum",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 48386bef75b5970fd986872e88c40ee393f43817 | 3bed6493a40205451fda6fafc4e2ca837f850ccb | |||
v1.0 | complete | Codeforces | Codeforces_11399_C | from typing import List, Tuple
def find_clusters(n: int, d: int, coords: List[Tuple[int, int]]) -> Tuple[int, List[int]]:
""" Find the number of clusters and the sizes of these clusters formed by birds within a given distance.
>>> find_clusters(10, 2, [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (-1, -1), (-2... | import math
from collections import defaultdict
def calculate_distance(bird1, bird2):
return math.sqrt((bird1[0] - bird2[0])**2 + (bird1[1] - bird2[1])**2)
def find_clusters(n, d, coords):
def dfs(bird_index, visited, cluster):
visited[bird_index] = True
cluster.append(bird_index)
for ... | from solution import find_clusters
def test_find_clusters_example():
n = 10
d = 2
coords = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (-1, -1), (-2, -2), (-3, -3), (-4, -4), (-5, -5)]
expected_clusters = 2
expected_sizes = [5, 5]
assert find_clusters(n, d, coords) == (expected_clusters, expected_... | [
{
"docstring": null,
"function_declaration": "def calculate_distance(bird1, bird2):",
"function_name": "calculate_distance",
"parameter_list": "(bird1, bird2)"
},
{
"docstring": null,
"function_declaration": "def find_clusters(n, d, coords):",
"function_name": "find_clusters",
"p... | [
1,
0,
0,
1,
1,
1,
0,
1,
1,
0
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef find_clusters(n, d, coordinates):\n \"\"\"\n Find the number of clusters and their sizes.\n \n Args:\n n (int) : Number of b... | trial_gpt4o_7 | {
"original_instruction": "A group of biologists is studying the movement patterns of a species of migratory birds. They have recorded the locations of these birds over a period of n days. On each day, the position of each bird is recorded as a point (x, y) on a 2D plane. Over time, they have hypothesized that birds ... | 0.640792 | Codeforces_11399 | C | [
"calculate_distance",
"find_clusters"
] | 2 | [
[
"find_clusters",
"calculate_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 27f1dbbc04815b2c26dc4a789edf931219698f05 | 3039aea0f7245c56cb8799a0d52cc5d311375d39 | |||
v1.0 | complete | Codeforces | Codeforces_10364_C | def can_form_palindrome_by_deleting_one_char(t, test_cases):
""" Determine if it is possible to delete exactly one character from the string
to make it a palindrome for each test case.
Args:
t (int): The number of test cases.
test_cases (List[str]): List of strings to be tested.
Return... | def can_form_palindrome_by_deleting_one_char(t, test_cases):
results = []
for s in test_cases:
if is_palindrome(s):
results.append("YES")
continue
found = False
length = len(s)
for i in range(length):
# Remove one charact... | from solution import can_form_palindrome_by_deleting_one_char, is_palindrome
def test_is_palindrome():
assert is_palindrome("aba") == True
assert is_palindrome("abca") == False
assert is_palindrome("a") == True
assert is_palindrome("") == True
assert is_palindrome("abccba") == True
def test_can_fo... | [
{
"docstring": null,
"function_declaration": "def can_form_palindrome_by_deleting_one_char(t, test_cases):",
"function_name": "can_form_palindrome_by_deleting_one_char",
"parameter_list": "(t, test_cases)"
},
{
"docstring": null,
"function_declaration": "def is_palindrome(s):",
"func... | [
1,
1,
0,
1,
1,
0,
0,
0,
0
] | 4 | medium | 0.444 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def can_become_palindrome_by_removing_one_char(s):\n \"\"\"\n Determine if it is possible to delete exactly one character from the string to make it a p... | trial_gpt4o_5 | {
"original_instruction": "You are given a string $$$s$$$ consisting of lowercase English letters. Your task is to determine if it is possible to delete exactly one character from the string to make it a palindrome. If it is possible, print \"YES\", otherwise, print \"NO\".\n\nA string is considered a palindrome if i... | 0.805094 | Codeforces_10364 | C | [
"can_form_palindrome_by_deleting_one_char",
"is_palindrome"
] | 2 | [
[
"can_form_palindrome_by_deleting_one_char",
"is_palindrome"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 81237ac55ab2428d86f113fe5dc972bff343d742 | 5e0744a98cfa5a2818a47125c871e6096fcb3856 | |||
v1.0 | complete | Codeforces | Codeforces_12546_C | def assign_types(n: int, k: int, edges: List[Tuple[int, int]]) -> Union[str, Tuple[str, List[int]]]:
"""
Determines if it is possible to assign types to each park such that no directly connected parks have the same type,
and returns the type assignment if possible.
Args:
- n: the number of parks
... | def assign_types(n, k, edges):
from collections import defaultdict, deque
if k == 1 and n > 1:
return "NO"
# Build the adjacency list
graph = defaultdict(list)
for u, v in edges:
graph[u].append(v)
graph[v].append(u)
# BFS to color the tree
types = [-1] * (... | from solution import solve
def test_example_case():
parks = 5
types = 3
connections = [(1, 2), (1, 3), (2, 4), (3, 5)]
solve(parks, types, connections)
assert True
def test_only_one_type_and_multiple_parks():
parks = 5
types = 1
connections = [(1, 2), (1, 3), (2, 4), (3, 5)]
assert... | [
{
"docstring": null,
"function_declaration": "def assign_types(n, k, edges):",
"function_name": "assign_types",
"parameter_list": "(n, k, edges)"
},
{
"docstring": null,
"function_declaration": "def solve(parks, types, connections):",
"function_name": "solve",
"parameter_list": "... | [
0,
1,
1,
1,
0,
0,
0,
0,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import deque\n\ndef can_assign_types(n, k, edges):\n if k == 1 and n > 1:\n return False, []\n \n # Create adjacency list for... | trial_gpt4o_1 | {
"original_instruction": "In a dense city, Bob is trying to create a network of public parks connected by pedestrian bridges. Each park has a unique integer ID. A pedestrian bridge can connect two parks bidirectionally, allowing people to walk between them. However, to minimize costs and maintenance, Bob wants to en... | 0.553275 | Codeforces_12546 | C | [
"assign_types",
"solve"
] | 2 | [
[
"solve",
"assign_types"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 440561d270866527bebf04f28dae02757277b0b8 | 7408ec4c2e78c01af28f3efa7996c9b2ba3f3c82 | |||
v1.0 | complete | Codeforces | Codeforces_13171_C | def minimum_cost_to_connect_houses(n: int, m: int, roads: List[Tuple[int, int, int]]) -> int:
"""
Determines the minimum total cost to build a network of roads to connect all houses in a village.
If it's impossible to connect all the houses, returns -1.
Args:
n (int): The number of houses.
... | def find(parent, i):
if parent[i] == i:
return i
else:
return find(parent, parent[i])
def union(parent, rank, x, y):
xroot = find(parent, x)
yroot = find(parent, y)
if rank[xroot] < rank[yroot]:
parent[xroot] = yroot
elif rank[xroot] > rank[yroot]:
parent[yr... | def test_simple_connected_case():
n, m = 4, 4
roads = [
(1, 2, 1),
(2, 3, 2),
(3, 4, 3),
(4, 1, 4)
]
assert minimum_cost_to_connect_houses(n, m, roads) == 6
def test_disconnected_case():
n, m = 4, 2
roads = [
(1, 2, 1),
(3, 4, 2)
]
assert ... | [
{
"docstring": null,
"function_declaration": "def find(parent, i):",
"function_name": "find",
"parameter_list": "(parent, i)"
},
{
"docstring": null,
"function_declaration": "def union(parent, rank, x, y):",
"function_name": "union",
"parameter_list": "(parent, rank, x, y)"
},
... | [
0,
1,
1,
1,
1,
1,
0,
0,
1,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def find(parent, i):\n if parent[i] == i:\n return i\n parent[i] = find(parent, parent[i])\n return parent[i]\n\ndef union(parent, rank, x, y)... | trial_gpt4o_9 | {
"original_instruction": "A small village is planning to build a network of roads to connect all its houses. The village has n houses and m potential roads that could be built. Each road connects exactly two houses and has a certain construction cost. The houses are numbered from 1 to n.\n\nThe village council has t... | 0.654089 | Codeforces_13171 | C | [
"find",
"union",
"minimum_cost_to_connect_houses"
] | 3 | [
[
"minimum_cost_to_connect_houses",
"find"
],
[
"minimum_cost_to_connect_houses",
"union"
],
[
"union",
"find"
]
] | 3 | [] | false | [] | false | pytest | false | [] | true | d96cd1c0d02e89d911deb346cf71b9e3683a5da6 | dcd49bc19c87dac751e39b9e090c7367e7d5c0cf | |||
v1.0 | complete | Codeforces | Codeforces_13634_C | def solve_grid_reach(m: int, n: int, grid: List[str], sx: int, sy: int, dx: int, dy: int) -> str:
""" Determine if the ball can reach the destination from the start position in an infinite number of moves.
m: number of rows in the grid
n: number of columns in the grid
grid: a list of strings representi... | def can_reach_destination(grid, start, destination):
m, n = len(grid), len(grid[0])
visited = [[False] * n for _ in range(m)]
def has_path(x, y, dx, dy):
if not (0 <= x < m and 0 <= y < n) or grid[x][y] == '#' or visited[x][y]:
return False
if (x, y) == (dx, dy):
... | from solution import solve_grid_reach
def test_example_1():
m, n = 5, 5
grid = [
".....",
".#...",
".###.",
".....",
".#..."
]
assert solve_grid_reach(m, n, grid, 1, 1, 4, 5) == "YES"
def test_example_2():
m, n = 3, 3
grid = [
".#.",
".#.... | [
{
"docstring": null,
"function_declaration": "def can_reach_destination(grid, start, destination):",
"function_name": "can_reach_destination",
"parameter_list": "(grid, start, destination)"
},
{
"docstring": null,
"function_declaration": "def solve_grid_reach(m, n, grid, sx, sy, dx, dy):... | [
1,
0,
0,
0,
1,
0,
1,
0,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def can_reach_destination(m, n, grid, sx, sy, dx, dy):\n def dfs(x, y, visited):\n if x == dx and y == dy:\n return True\n visited... | trial_gpt4o_6 | {
"original_instruction": "You are given a rectangular grid of size m x n consisting of blank cells (represented by '.') and some obstacle cells (represented by '#'). A ball can move up, down, left, or right, but it will stop moving once it encounters an obstacle or the edge of the grid. \n\nGiven the starting positi... | 0.669708 | Codeforces_13634 | C | [
"can_reach_destination",
"solve_grid_reach"
] | 2 | [
[
"solve_grid_reach",
"can_reach_destination"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1e6898ed93fc807882406212d4b6a33f4808ab2e | 7011ac383bb8b4dc0e62cd19f19478828263e6ae | |||
v1.0 | complete | Codeforces | Codeforces_11166_C | def find_redundant_connections(n, m, connections):
""" Mira wants to design a new video game with an expansive world map consisting of interconnected dungeons.
Each dungeon is represented as a node, and each direct path between two dungeons is represented as an undirected edge.
Mira needs to ensure that th... | def find_redundant_connections(n, m, connections):
parent = list(range(n + 1))
def find(x):
if parent[x] != x:
parent[x] = find(parent[x])
return parent[x]
def union(x, y):
rootX = find(x)
rootY = find(y)
if rootX != rootY:
parent[rootY] = ro... | import pytest
from solution import handle_io
def test_example():
input_data = "5 6\n1 2\n1 3\n2 3\n2 4\n3 4\n4 5"
expected_output = "2\n2 3\n3 4"
assert handle_io(input_data) == expected_output
def test_no_connections():
input_data = "5 0"
expected_output = "0"
assert handle_io(input_data) == ... | [
{
"docstring": null,
"function_declaration": "def find_redundant_connections(n, m, connections):",
"function_name": "find_redundant_connections",
"parameter_list": "(n, m, connections)"
},
{
"docstring": null,
"function_declaration": "def handle_io(input_data):",
"function_name": "ha... | [
0,
1,
1,
0,
0,
1,
0,
1,
0,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def find_redundant_connections(n, m, connections):\n from collections import defaultdict, deque\n \n def build_graph(n, connections):\n graph ... | trial_gpt4o_5 | {
"original_instruction": "Mira wants to design a new video game with an expansive world map consisting of interconnected dungeons. Each dungeon is represented as a node, and each direct path between two dungeons is represented as an undirected edge. Mira needs to ensure that the game player can reach every dungeon f... | 0.541764 | Codeforces_11166 | C | [
"find_redundant_connections",
"handle_io"
] | 2 | [
[
"handle_io",
"find_redundant_connections"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f799d729613c3c76556b36ce13ab0848077a7585 | 4aea3623f86d287d7d954ef79fcbb956f7057de4 | |||
v1.0 | complete | Codeforces | Codeforces_10651_C | from typing import List, Tuple
def shortest_path(xA: int, yA: int, xB: int, yB: int, obstacles: List[Tuple[int, int, int, int]]) -> int:
"""
Determines the shortest path from point A to point B avoiding obstacles.
Args:
xA: int - x-coordinate of point A
yA: int - y-coordinate of point A
x... | from collections import deque
def is_point_within_any_obstacle(x, y, obstacles):
for x1, y1, x2, y2 in obstacles:
if x1 <= x <= x2 and y1 <= y <= y2:
return True
return False
def shortest_path(xA, yA, xB, yB, obstacles):
if (xA, yA) == (xB, yB):
return 0
if is_point_within... | import pytest
from solution import shortest_path
def test_no_obstacles_direct_path():
assert shortest_path(0, 0, 5, 5, []) == 10
def test_with_obstacles():
obstacles = [(2, 2, 4, 4), (5, 5, 7, 7)]
assert shortest_path(0, 0, 10, 10, obstacles) == 20
def test_start_point_in_obstacle():
obstacles = [(2,... | [
{
"docstring": null,
"function_declaration": "def is_point_within_any_obstacle(x, y, obstacles):",
"function_name": "is_point_within_any_obstacle",
"parameter_list": "(x, y, obstacles)"
},
{
"docstring": null,
"function_declaration": "def shortest_path(xA, yA, xB, yB, obstacles):",
"... | [
0,
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import heapq\nfrom collections import deque\n\ndef is_inside_rect(x, y, rect):\n return rect[0] <= x <= rect[2] and rect[1] <= y <= rect[3]\n\ndef shortest... | trial_gpt4o_7 | {
"original_instruction": "A telecommunications company is laying high-speed fiber optic cables in a specific city. The city's layout is a grid of streets, represented by a 2D plane with intersections at integer coordinates. However, there are certain obstacles where the cable cannot be laid. These obstacles are give... | 0.59725 | Codeforces_10651 | C | [
"is_point_within_any_obstacle",
"shortest_path"
] | 2 | [
[
"shortest_path",
"is_point_within_any_obstacle"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | fde57c1e0e46d78cd0aa28ba636adaf586a74c70 | 4406a26c580e7d2ec3285822d3de8a686c165f2e | |||
v1.0 | complete | Codeforces | Codeforces_12451_C | import math
from typing import Tuple
def calculate_distance(point1: Tuple[int, int], point2: Tuple[int, int]) -> float:
return math.sqrt((point2[0] - point1[0])**2 + (point2[1] - point1[1])**2)
def can_complete_route(S: int, R: Tuple[int, int], F: Tuple[int, int], W: Tuple[int, int]) -> bool:
"""
Determin... | import math
def calculate_distance(point1, point2):
return math.sqrt((point2[0] - point1[0])**2 + (point2[1] - point1[1])**2)
def can_complete_route(S, R, F, W):
"""
Determines if the route R -> F -> W -> R can be completed within the stamina limit S.
Parameters:
- S: int, the stamina limit.
... | from solution import can_complete_route
def test_example_case():
S = 25
R = (0, 0)
F = (3, 4)
W = (6, 8)
assert can_complete_route(S, R, F, W) == True
def test_case_exceeding_stamina():
S = 15
R = (0, 0)
F = (3, 4)
W = (6, 8)
assert can_complete_route(S, R, F, W) == False
... | [
{
"docstring": null,
"function_declaration": "def calculate_distance(point1, point2):",
"function_name": "calculate_distance",
"parameter_list": "(point1, point2)"
},
{
"docstring": "Determines if the route R -> F -> W -> R can be completed within the stamina limit S.\n\nParameters:\n- S: in... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef distance(p1, p2):\n \"\"\"\n Calculate the Euclidean distance between two points.\n \"\"\"\n return math.sqrt((p1[0] - p2[0]) *... | trial_gpt4o_8 | {
"original_instruction": "Alyssa is designing an amusement park layout. The park consists of three main attractions: a roller coaster, a Ferris wheel, and a water ride. She wants to create walking paths connecting these attractions, but needs to ensure that the paths cover certain constraints. \n\nAlyssa starts at t... | 0.618086 | Codeforces_12451 | C | [
"calculate_distance",
"can_complete_route"
] | 2 | [
[
"can_complete_route",
"calculate_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e2fd629e58985b4f7897b8d03cca8637d33ba222 | 80082a34f2956c4d94ec1fff8941adef4ce635af | |||
v1.0 | complete | Codeforces | Codeforces_14523_C | def min_weight_difference(n: int, m: int, edge_list: List[Tuple[int, int, int]]) -> int:
"""
Given an undirected graph with n nodes and m edges, find the minimum
possible weight difference between the heaviest and the lightest edge
in the resulting tree after removing the necessary edges.
>>... | def find(parent, i):
if parent[i] == i:
return i
return find(parent, parent[i])
def union(parent, rank, x, y):
root_x = find(parent, x)
root_y = find(parent, y)
if root_x != root_y:
if rank[root_x] > rank[root_y]:
parent[root_y] = root_x
elif rank[root_x] < rank[... | def test_min_weight_difference_sample():
assert min_weight_difference(6, 7, [
(1, 2, 3),
(2, 3, 3),
(3, 4, 5),
(4, 5, 6),
(5, 6, 7),
(1, 6, 8),
(1, 3, 2)
]) == 4
def test_min_weight_difference_tree():
assert min_weight_difference(4, 3, [
(1, ... | [
{
"docstring": null,
"function_declaration": "def find(parent, i):",
"function_name": "find",
"parameter_list": "(parent, i)"
},
{
"docstring": null,
"function_declaration": "def union(parent, rank, x, y):",
"function_name": "union",
"parameter_list": "(parent, rank, x, y)"
},
... | [
0,
0,
0,
0,
1,
0,
0,
0,
0,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def minimum_weight_difference(n, m, edges):\n \"\"\"\n Finds the minimum possible weight difference between the heaviest and the lightest edge \n in ... | trial_gpt4o_9 | {
"original_instruction": "You are given an undirected graph with n nodes and m edges. Each edge has a weight associated with it. Your task is to remove some of the edges so that the remaining edges form a tree that has the minimum possible weight difference between the heaviest and the lightest edge in the resulting... | 0.71 | Codeforces_14523 | C | [
"find",
"union",
"kruskal",
"min_weight_difference"
] | 4 | [
[
"kruskal",
"find"
],
[
"kruskal",
"union"
],
[
"min_weight_difference",
"kruskal"
],
[
"union",
"find"
]
] | 4 | [] | false | [] | false | pytest | false | [] | true | 225c9f628fb8b001d244b1114553bfa890f03de3 | 34dff408955077ee248b2efd0b68f1a44079c021 | |||
v1.0 | complete | Codeforces | Codeforces_11717_C | import math
from typing import List, Tuple
def haversine(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
""" Calculate the great-circle distance between two points
on the Earth's surface given their latitude and longitude in degrees.
>>> round(haversine(40.730610, -73.935242, 40.730611, ... | import math
def haversine(lat1, lon1, lat2, lon2):
# Radius of the Earth in kilometers
R = 6371.0
# Convert latitude and longitude from degrees to radians
lat1_rad = math.radians(lat1)
lon1_rad = math.radians(lon1)
lat2_rad = math.radians(lat2)
lon2_rad = math.radians(lon2)
# ... | from solution import haversine, total_distance_traveled, main
def test_haversine():
assert round(haversine(40.730610, -73.935242, 40.730611, -73.935200), 2) == 0.00
assert round(haversine(34.052235, -118.243683, 34.052245, -118.243679), 2) == 0.00
assert round(haversine(0, 0, 0, 1), 2) == 111.19 # Approxi... | [
{
"docstring": null,
"function_declaration": "def haversine(lat1, lon1, lat2, lon2):",
"function_name": "haversine",
"parameter_list": "(lat1, lon1, lat2, lon2)"
},
{
"docstring": null,
"function_declaration": "def total_distance_traveled(bird_coordinates):",
"function_name": "total_... | [
0,
0,
0,
0,
1,
0,
0,
0,
0
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef haversine_distance(lat1, lon1, lat2, lon2):\n R = 6371 # Earth's radius in km\n \n # Convert latitude and longitude from degrees ... | trial_gpt4o_5 | {
"original_instruction": "A group of biologists is studying the migration patterns of a species of birds. Each bird is equipped with a GPS tracker that records its latitude and longitude every minute of its flight. The biologists have the coordinates recorded for each bird at each minute interval over a period of on... | 0.576149 | Codeforces_11717 | C | [
"haversine",
"total_distance_traveled",
"main"
] | 3 | [
[
"total_distance_traveled",
"haversine"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c71784600d23e66467bd171dc40fee2605f0b0bf | 979d827db7bc2b3172862cf2866530e7ec6825bc | |||
v1.0 | complete | Codeforces | Codeforces_12639_C | def can_watch_all_movies(screenings: list) -> str:
"""
Determines if a person can watch all movies without any schedule conflicts
based on the provided screenings.
Args:
screenings (list of tuples): Each tuple contains three integers, start time,
end time, and m... | def can_watch_all_movies(screenings):
"""
Determines if a person can watch all movies without any schedule conflicts
based on the provided screenings.
Args:
screenings (list of tuples): Each tuple contains three integers, start time,
end time, and movie ID for e... | from solution import can_watch_all_movies, process_input, solve
def test_can_watch_all_movies_possible():
screenings = [(60, 120, 1), (130, 170, 2), (180, 240, 3)]
assert can_watch_all_movies(screenings) == "Possible"
def test_can_watch_all_movies_impossible():
screenings = [(60, 120, 1), (100, 140, 2), (... | [
{
"docstring": "Determines if a person can watch all movies without any schedule conflicts\nbased on the provided screenings.\n\nArgs:\nscreenings (list of tuples): Each tuple contains three integers, start time,\n end time, and movie ID for each screening.\n\nReturns:\nstr: \"Possib... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def can_watch_all_movies(screenings):\n \"\"\"\n Determine if it's possible to watch all movies without any scheduling conflicts.\n\n :param screenin... | trial_gpt4o_9 | {
"original_instruction": "You are hired to develop a streamlined ticketing system for a small movie theater that is handling multiple screenings throughout the day. Each screening has a start time, an end time, and a movie ID. You are required to determine if a person can watch all movies without any schedule confli... | 0.536127 | Codeforces_12639 | C | [
"can_watch_all_movies",
"process_input",
"solve"
] | 3 | [
[
"solve",
"can_watch_all_movies"
],
[
"solve",
"process_input"
]
] | 2 | [
"process_input"
] | false | [] | false | pytest | true | [] | true | 9c548f06e2c7dc2449f7d36e692ac0bdcf426494 | 48c7e682a7d654471c16082294dbc62053caf131 | |||
v1.0 | complete | Codeforces | Codeforces_12125_C | class TreeNode:
def __init__(self, value=0, left=None, right=None):
self.value = value
self.left = left
self.right = right
def build_tree(nodes):
tree_nodes = [None] * len(nodes)
for i in range(len(nodes)):
tree_nodes[i] = TreeNode(nodes[i][0])
for i in range(len(nodes))... | class TreeNode:
def __init__(self, value=0, left=None, right=None):
self.value = value
self.left = left
self.right = right
def build_tree(nodes):
tree_nodes = [None] * len(nodes)
for i in range(len(nodes)):
tree_nodes[i] = TreeNode(nodes[i][0])
for i in range(len(nodes))... | from solution import find_largest_subtree_sum
def test_example():
n = 5
nodes = [
(1, 2, 3),
(2, -1, -1),
(3, 4, -1),
(4, -1, 5),
(5, -1, -1)
]
assert find_largest_subtree_sum(n, nodes) == 15
def test_single_node():
n = 1
nodes = [
(10, -1, -1)
... | [] | [
0,
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, value=0, left=None, right=None):\n self.value = value\n self.left = left\n self.right = right\n\n... | trial_gpt4o_7 | {
"original_instruction": "You are given a binary tree where each node contains a value. We need to find the largest sum of a subtree where a subtree is defined as a node and all its descendants, and the value of the subtree is the sum of values of all the nodes within it.\n\n## Requirements\n\n**Input:**\n- The inpu... | 0.591045 | Codeforces_12125 | C | [
"build_tree",
"max_subtree_sum",
"find_largest_subtree_sum"
] | 3 | [
[
"find_largest_subtree_sum",
"build_tree"
],
[
"find_largest_subtree_sum",
"max_subtree_sum"
]
] | 2 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 1f5cc3166b7d3638d8421ed017cd38c6a5a2079f | 1c0554780eabb12b8977343826b4a9abe7e71c64 | |||
v1.0 | complete | Codeforces | Codeforces_14832_C | from typing import List, Tuple
def maximize_harmony(n: int, preferences: List[Tuple[int, ...]]) -> Tuple[int, List[int]]:
""" Aria enjoys organizing events and planning seating arrangements. She is organizing a round table event where people will be seated around a circular table, all facing the center.
Aria w... | from itertools import permutations
def count_preferences(seating, preferences):
count = 0
n = len(seating)
for i in range(n):
left = seating[i]
right = seating[(i + 1) % n]
if right in preferences[left]:
count += 1
if left in preferences[right]:
count... | from solution import maximize_harmony
def test_maximize_harmony_example():
assert maximize_harmony(4, [(2, 2, 3), (1, 1), (1, 4), (1, 1)]) == (3, [1, 2, 3, 4]) or (3, [4, 1, 2, 3])
def test_maximize_harmony_all_no_pref():
assert maximize_harmony(3, [(0,), (0,), (0,)]) == (0, [1, 2, 3]) or (0, [3, 1, 2]) or (0... | [
{
"docstring": null,
"function_declaration": "def count_preferences(seating, preferences):",
"function_name": "count_preferences",
"parameter_list": "(seating, preferences)"
},
{
"docstring": null,
"function_declaration": "def maximize_harmony(n, preferences):",
"function_name": "max... | [
0,
0,
0,
0,
0,
0,
0,
1,
0
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": null,
"trial_gpt4o_1": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared1_results_combined.jsonl",
"solution_code": "from itertools import permutations\n\ndef count_satisfied_preferences(arrangement, preferences):\n n = len(arrangement)\n satis... | trial_gpt4o_8 | {
"original_instruction": "Aria enjoys organizing events and planning seating arrangements. She is organizing a round table event where people will be seated around a circular table, all facing the center. Aria wants to carefully assign seats to ensure maximum harmony among the guests, considering their preferences.\... | 0.593909 | Codeforces_14832 | C | [
"count_preferences",
"maximize_harmony"
] | 2 | [
[
"maximize_harmony",
"count_preferences"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | fcc0e0901597034bdc5132ea1774cb1d073a2fab | f3f548c2120d1a6df7b9189de73a29589bd9f37e | |||
v1.0 | complete | Codeforces | Codeforces_13139_C | from collections import defaultdict, deque
import math
def preprocess_lca(n, edges):
LOG = math.ceil(math.log2(n)) + 1
parent = [[-1] * LOG for _ in range(n + 1)]
depth = [0] * (n + 1)
graph = defaultdict(list)
for u, v in edges:
graph[u].append(v)
graph[v].append(u)
def d... | from collections import defaultdict, deque
import sys
import math
sys.setrecursionlimit(200000)
def preprocess_lca(n, edges):
LOG = math.ceil(math.log2(n)) + 1
parent = [[-1] * LOG for _ in range(n + 1)]
depth = [0] * (n + 1)
graph = defaultdict(list)
for u, v in edges:
graph[u].appen... | from solution import solve
def test_example():
n = 5
edges = [(1, 2), (1, 3), (3, 4), (3, 5)]
queries = [(2, 3), (4, 5), (2, 4)]
assert solve(n, edges, queries) == [1, 3, 1]
def test_small_tree():
n = 3
edges = [(1, 2), (1, 3)]
queries = [(2, 3)]
assert solve(n, edges, queries) == [1]
... | [
{
"docstring": null,
"function_declaration": "def preprocess_lca(n, edges):",
"function_name": "preprocess_lca",
"parameter_list": "(n, edges)"
},
{
"docstring": null,
"function_declaration": "def lca(u, v, depth, parent):",
"function_name": "lca",
"parameter_list": "(u, v, depth... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import sys\nimport collections\n\n# A function to perform Depth-First Search for setting up depths and ancestors\ndef dfs(node, parent, depth, depths, ancesto... | trial_gpt4o_8 | {
"original_instruction": "Annie is working as a software developer and has been assigned to work on a project involving hierarchical data processing using trees. As part of this, she needs to write an efficient algorithm to find the Lowest Common Ancestor (LCA) of two nodes in a tree. The LCA of two nodes \\(u\\) an... | 0.56359 | Codeforces_13139 | C | [
"preprocess_lca",
"lca",
"solve"
] | 3 | [
[
"solve",
"lca"
],
[
"solve",
"preprocess_lca"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 2ddfd080fd6f0b4790cba4a0b6f8a58846bcb1c6 | c0a47840d83d0d83da40c6e75028f7e4f57009c4 | |||
v1.0 | complete | Codeforces | Codeforces_12062_C | from collections import defaultdict, deque
from typing import List, Tuple
def preprocess_ancestors(n: int, edges: List[Tuple[int, int]]) -> dict:
# Placeholder for preprocessing logic
pass
def find_kth_ancestor(ancestors: dict, u: int, k: int) -> int:
# Placeholder for finding kth ancestor
pass
def p... | from collections import defaultdict, deque
def preprocess_ancestors(n, edges):
# Initialize the tree and parent dictionary
tree = defaultdict(list)
for a, b in edges:
tree[a].append(b)
tree[b].append(a)
# Ancestor table
ancestors = {i: [] for i in range(1, n + 1)}
# BF... | from solution import process_queries
def test_sample():
n = 5
values = [10, 20, 30, 40, 50]
edges = [(1, 2), (1, 3), (2, 4), (2, 5)]
queries = [(4, 1), (5, 2), (3, 1), (3, 3)]
expected_output = [2, 1, 1, -1]
assert process_queries(n, values, edges, queries) == expected_output
def test_no_ances... | [
{
"docstring": null,
"function_declaration": "def preprocess_ancestors(n, edges):",
"function_name": "preprocess_ancestors",
"parameter_list": "(n, edges)"
},
{
"docstring": null,
"function_declaration": "def find_kth_ancestor(ancestors, u, k):",
"function_name": "find_kth_ancestor",... | [
1,
0,
1,
0,
0,
1,
1,
1,
0,
0
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def find_kth_ancestor(n, values, edges, q, queries):\n import sys\n sys.setrecursionlimit(200000)\n \n from collections import defaultdict, deque\... | trial_gpt4o_7 | {
"original_instruction": "You are given a tree with n nodes rooted at node 1. Each node i has a value vi associated with it. You need to answer q queries. Each query is described by two integers u and k, where you are required to find the k-th ancestor of node u. If node u does not have a k-th ancestor, output -1.\n... | 0.57991 | Codeforces_12062 | C | [
"preprocess_ancestors",
"find_kth_ancestor",
"process_queries"
] | 3 | [
[
"process_queries",
"find_kth_ancestor"
],
[
"process_queries",
"preprocess_ancestors"
]
] | 2 | [
"process_queries"
] | false | [] | false | pytest | true | [] | true | 6d8eaf3f00a53f20002948092eb87c8a4c524f99 | b81b8ac17a9000af313b7ca662a68a3cd61ff9a9 | |||
v1.0 | complete | Codeforces | Codeforces_10878_C | def can_make_all_recipes(ingredients, quantities, recipes):
"""Determine whether Chef can prepare all the recipes in the list given the stock of ingredients in the pantry.
Args:
ingredients: List of ingredient names in the pantry.
quantities: List of quantities corresponding to the ingredients in t... | def can_make_all_recipes(ingredients, quantities, recipes):
ingredient_stock = dict(zip(ingredients, quantities))
for recipe in recipes:
for ingredient, quantity in recipe.items():
if ingredient not in ingredient_stock or ingredient_stock[ingredient] < quantity:
return "... | import pytest
from solution import chef_recipes
def test_chef_recipes_yes():
input_data = """5
sugar flour butter eggs milk
500 300 200 5 1000
2
3
sugar 200
flour 100
butter 5... | [
{
"docstring": null,
"function_declaration": "def can_make_all_recipes(ingredients, quantities, recipes):",
"function_name": "can_make_all_recipes",
"parameter_list": "(ingredients, quantities, recipes)"
},
{
"docstring": null,
"function_declaration": "def parse_input(input_string):",
... | [
0,
1,
1,
1,
0,
1,
1,
1,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def can_cook_all_recipes(pantry_ingredients, pantry_quantities, recipes):\n # Convert the pantry ingredients and quantities into a dictionary\n pantry =... | trial_gpt4o_8 | {
"original_instruction": "Chef is a budding gourmet who is learning to cook using various ingredients. Chef maintains a recipe book where each recipe lists the required ingredients and the quantity of each ingredient needed. Chef has a pantry with a limited stock of ingredients. \n\nGiven a list of recipes Chef want... | 0.643397 | Codeforces_10878 | C | [
"can_make_all_recipes",
"parse_input",
"chef_recipes"
] | 3 | [
[
"chef_recipes",
"can_make_all_recipes"
],
[
"chef_recipes",
"parse_input"
]
] | 2 | [
"parse_input"
] | false | [] | false | pytest | true | [] | true | a52f6ca5c17e8d90407c6f47995b9f59091f849e | 0ba86f2bc190c4d5361f3b80feee864832f111fa | |||
v1.0 | complete | Codeforces | Codeforces_10968_C | import heapq
import sys
from typing import List, Tuple
def shortest_path(n: int, edges: List[Tuple[int, int, int]], src: int, dst: int) -> int:
""" Find the shortest path between two nodes in an undirected graph.
>>> shortest_path(4, [(1, 2, 1), (2, 3, 2), (3, 4, 3), (1, 4, 10)], 1, 4)
6
>>> shortest_p... | from heapq import heappop, heappush
import sys
def shortest_path(n, edges, src, dst):
graph = {i: [] for i in range(1, n + 1)}
for u, v, l in edges:
graph[u].append((v, l))
graph[v].append((u, l))
distances = {i: sys.maxsize for i in range(1, n + 1)}
distances[src] = 0
priority_que... | def test_shortest_path():
input_lines = [
"2",
"4 4",
"1 2 1",
"2 3 2",
"3 4 3",
"1 4 10",
"1 4",
"4 2",
"1 2 5",
"1 3 2",
"1 4"
]
expected_output = [6, -1]
assert find_shortest_paths(input_lines) == expected_output
... | [
{
"docstring": null,
"function_declaration": "def shortest_path(n, edges, src, dst):",
"function_name": "shortest_path",
"parameter_list": "(n, edges, src, dst)"
},
{
"docstring": null,
"function_declaration": "def process_test_cases(test_cases):",
"function_name": "process_test_case... | [
1,
0,
1,
0,
0,
1,
0,
1,
0,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import heapq\nimport sys\n\ndef dijkstra(n, graph, src, dst):\n # Distance to all nodes set to \"infinity\"\n dist = {i: sys.maxsize for i in range(1, n... | trial_gpt4o_9 | {
"original_instruction": "You are given an undirected graph with `n` nodes and `m` edges. Each edge has a positive length. You need to find the shortest path between two nodes in this graph. The graph may contain cycles, and all nodes are numbered from 1 to `n`.\n\nThe input consists of multiple test cases. For each... | 0.616426 | Codeforces_10968 | C | [
"shortest_path",
"process_test_cases",
"find_shortest_paths"
] | 3 | [
[
"find_shortest_paths",
"process_test_cases"
],
[
"process_test_cases",
"shortest_path"
]
] | 2 | [
"process_test_cases"
] | false | [] | false | pytest | false | [] | true | ac2920e187a3daae7ecc09f3247f2234deec631a | db17f68af740f4da066c82234e3e1dc956befae0 | |||
v1.0 | complete | Codeforces | Codeforces_20047_C | def is_subsequence(s: str, word: str) -> bool:
it = iter(s)
return all(char in it for char in word)
def count_subsequences(s: str, words: List[str]) -> int:
"""
Counts how many words in the list are subsequences of the string `s`.
>>> count_subsequences("abcdefg", ["abc", "abg", "bdf", "acb", "bgf... | def is_subsequence(s, word):
it = iter(s)
return all(char in it for char in word)
def count_subsequences(s, words):
"""
Counts how many words in the list are subsequences of the string `s`.
"""
return sum(is_subsequence(s, word) for word in words) | from solution import count_subsequences
def test_example_case():
s = "abcdefg"
words = ["abc", "abg", "bdf", "acb", "bgf"]
assert count_subsequences(s, words) == 3
def test_single_char_words():
s = "abc"
words = ["a", "b", "c", "d"]
assert count_subsequences(s, words) == 3
def test_identical_... | [
{
"docstring": null,
"function_declaration": "def is_subsequence(s, word):",
"function_name": "is_subsequence",
"parameter_list": "(s, word)"
},
{
"docstring": "Counts how many words in the list are subsequences of the string `s`.",
"function_declaration": "def count_subsequences(s, word... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005484_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import defaultdict\n\ndef num_matching_subseq(s, words):\n \"\"\"\n Given a string s and a list of words, returns the number of words t... | trial_gpt4o_2 | {
"original_instruction": "You are given a string `s` consisting of lowercase English letters and a set of `words` consisting of non-empty strings made of lowercase English letters. The task is to count how many of the words from the `words` list are subsequences of the string `s`.\n\nA subsequence is a sequence that... | 0.731761 | Codeforces_20047 | C | [
"is_subsequence",
"count_subsequences"
] | 2 | [
[
"count_subsequences",
"is_subsequence"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6ec7af35a7431d38beaba337c70a94df6919418d | e0f8dd22199935e2ccb3a23f227208976e4802ea | |||
v1.0 | complete | Codeforces | Codeforces_20113_C | def nth_alternating_prime_sum(n: int) -> int:
"""
Calculates the n-th term of Frank's "alternating prime sum" sequence.
Args:
n (int): The term number to compute (1 ≤ n ≤ 1000).
Returns:
int: The value of the alternating prime sum sequence at the n-th term.
>>> nth_alternating... | def is_prime(num):
if num <= 1:
return False
if num <= 3:
return True
if num % 2 == 0 or num % 3 == 0:
return False
i = 5
while i * i <= num:
if num % i == 0 or num % (i + 2) == 0:
return False
i += 6
return True
def nth_alternating_prime_sum(... | from solution import nth_alternating_prime_sum
def test_nth_alternating_prime_sum_1():
assert nth_alternating_prime_sum(1) == 2
def test_nth_alternating_prime_sum_2():
assert nth_alternating_prime_sum(2) == -1
def test_nth_alternating_prime_sum_3():
assert nth_alternating_prime_sum(3) == 4
def test_nth_... | [
{
"docstring": null,
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "Calculates the n-th term of Frank's \"alternating prime sum\" sequence.\n\nArgs:\nn (int): The term number to compute (1 ≤ n ≤ 1000).\n\nReturns:\nint:... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005484_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(num):\n if num <= 1:\n return False\n if num <= 3:\n return True\n if num % 2 == 0 or num % 3 == 0:\n return False\... | trial_gpt4o_0 | {
"original_instruction": "Frank has an unusual prime number obsession. He collects prime numbers in a special sequence called \"alternating prime sum\". The alternating prime sum sequence is defined as follows:\n\nThe first prime number in the sequence is 2. \nThe second prime is subtracted from the first, the third... | 0.625381 | Codeforces_20113 | C | [
"is_prime",
"nth_alternating_prime_sum"
] | 2 | [
[
"nth_alternating_prime_sum",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e0d18fab4d1281efa90f589141ea7e323ccc0f74 | 2b974e13d005c2e3a4584a740db0ccac3f9eaf92 | |||
v1.0 | complete | Codeforces | Codeforces_20193_C | from typing import List
def find_min_max_pages(books: List[int], n: int, k: int) -> int:
""" Find the minimum possible value of the maximum number of pages assigned to any student.
Arguments:
books -- an array of integers where each integer represents the number of pages in a book
n -- the number ... | def is_possible(books, n, k, max_pages):
students_required = 1
current_pages = 0
for pages in books:
if current_pages + pages > max_pages:
students_required += 1
current_pages = pages
if students_required > k:
return False
else:
... | def test_find_min_max_pages_case_1():
books = [12, 34, 67, 90]
k = 2
assert find_min_max_pages(books, len(books), k) == 113
def test_find_min_max_pages_case_2():
books = [10, 20, 30, 40]
k = 2
assert find_min_max_pages(books, len(books), k) == 60
def test_find_min_max_pages_case_3():
books... | [
{
"docstring": null,
"function_declaration": "def is_possible(books, n, k, max_pages):",
"function_name": "is_possible",
"parameter_list": "(books, n, k, max_pages)"
},
{
"docstring": null,
"function_declaration": "def find_min_max_pages(books, n, k):",
"function_name": "find_min_max... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005484_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_possible(books, n, k, curr_min):\n students_required = 1\n current_sum = 0\n\n for i in range(n):\n if books[i] > curr_min:\n ... | trial_gpt4o_1 | {
"original_instruction": "You are given an array of integers that represents the number of pages in different books. You have k students, and you want to allocate all the books to these students such that each student gets at least one book and the maximum number of pages assigned to a student is minimized.\n\nThe t... | 0.646784 | Codeforces_20193 | C | [
"is_possible",
"find_min_max_pages"
] | 2 | [
[
"find_min_max_pages",
"is_possible"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 05d9fd12cd5319cd9c4009680fad3cd561abaefe | 87a4df3d92408938ab324635edb80a8da83d42a3 | |||
v1.0 | complete | Codeforces | Codeforces_20108_C | from typing import List, Tuple
def minimum_travel_time(n: int, roads: List[Tuple[int, int, int]]) -> int:
""" Determine the minimum travel time required to make the entire road network connected.
Parameters:
n (int): Number of intersections
roads (List[Tuple[int, int, int]]): List of roads where e... | def find(parent, i):
if parent[i] == i:
return i
else:
return find(parent, parent[i])
def union(parent, rank, x, y):
xroot = find(parent, x)
yroot = find(parent, y)
if rank[xroot] < rank[yroot]:
parent[xroot] = yroot
elif rank[xroot] > rank[yroot]:
parent[yr... | def test_basic_scenario():
n = 4
roads = [
(1, 2, 3),
(2, 3, 4),
(3, 4, 5),
(1, 4, 10)
]
assert minimum_travel_time(n, roads) == 12
def test_no_roads():
n = 4
roads = []
assert minimum_travel_time(n, roads) == -1
def test_single_road():
n = 2
roads =... | [
{
"docstring": null,
"function_declaration": "def find(parent, i):",
"function_name": "find",
"parameter_list": "(parent, i)"
},
{
"docstring": null,
"function_declaration": "def union(parent, rank, x, y):",
"function_name": "union",
"parameter_list": "(parent, rank, x, y)"
},
... | [
0,
1
] | 1 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005484_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def minimum_total_travel_time(n, m, roads):\n \"\"\"\n Determines the minimum total travel time required to ensure that every intersection\n is reach... | trial_gpt4o_1 | {
"original_instruction": "A small city is planning to build a new road network. There are n intersections in the city, numbered from 1 to n. Some pairs of intersections are already connected directly by bi-directional roads. Each road has a specific travel time associated with it. The city planner needs to ensure th... | 0.679893 | Codeforces_20108 | C | [
"find",
"union",
"kruskal",
"minimum_travel_time"
] | 4 | [
[
"kruskal",
"find"
],
[
"kruskal",
"union"
],
[
"minimum_travel_time",
"kruskal"
],
[
"union",
"find"
]
] | 4 | [] | false | [] | false | pytest | false | [] | true | f7655ca73212de04fbefb4a7b9945ce48d404458 | c0bf7dbfec2853c0cbe0d39bc2f164b5584c5f6a | |||
v1.0 | complete | Codeforces | Codeforces_20087_C | from typing import List, Tuple
def preprocess_matrix(matrix: List[List[int]]) -> List[List[int]]:
"""
Preprocess the matrix using prefix sums for efficient submatrix sum queries.
"""
pass
def submatrix_sum(prefix_sum: List[List[int]], i1: int, j1: int, i2: int, j2: int) -> int:
"""
Calculate t... | def preprocess_matrix(matrix):
"""
Preprocess the matrix using prefix sums for efficient submatrix sum queries.
"""
n = len(matrix)
m = len(matrix[0])
prefix_sum = [[0] * (m + 1) for _ in range(n + 1)]
for i in range(1, n + 1):
for j in range(1, m + 1):
prefix_sum[i][j] ... | from solution import preprocess_matrix, submatrix_sum, handle_queries
def test_preprocess_matrix():
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
expected_prefix_sum = [
[0, 0, 0, 0],
[0, 1, 3, 6],
[0, 5, 12, 21],
[0, 12, 27, 45]
]
assert prepr... | [
{
"docstring": "Preprocess the matrix using prefix sums for efficient submatrix sum queries.",
"function_declaration": "def preprocess_matrix(matrix):",
"function_name": "preprocess_matrix",
"parameter_list": "(matrix)"
},
{
"docstring": "Calculate the sum of the submatrix using the precompu... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005484_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def build_prefix_sum_matrix(matrix):\n n = len(matrix)\n m = len(matrix[0]) if n > 0 else 0\n prefix_sum = [[0] * (m + 1) for _ in range(n + 1)]\n ... | trial_gpt4o_2 | {
"original_instruction": "You are given a matrix of size \\( n \\times m \\) filled with non-negative integers. Your task is to find the sum of elements in the submatrix defined by its top-left and bottom-right corners. The top-left corner is at \\((i_1, j_1)\\) and the bottom-right corner is at \\((i_2, j_2)\\).\n\... | 0.561347 | Codeforces_20087 | C | [
"preprocess_matrix",
"submatrix_sum",
"handle_queries"
] | 3 | [
[
"handle_queries",
"preprocess_matrix"
],
[
"handle_queries",
"submatrix_sum"
]
] | 2 | [
"handle_queries"
] | false | [] | false | pytest | true | [] | true | df8938ee64edbc7d0a2437042b7d7b3f7d16f34b | 4d33e18a9a1fc2df9d9f52b914380ae23c9d9823 | |||
v1.0 | complete | Codeforces | Codeforces_20161_C | from typing import List
def is_prime(num: int) -> bool:
""" Helper function to check if a number is prime.
>>> is_prime(2)
True
>>> is_prime(4)
False
>>> is_prime(17)
True
"""
pass
def count_prime_product_subsets(primes: List[int]) -> int:
""" Function to count subsets whose pr... | def is_prime(num):
"""Helper function to check if a number is prime."""
if num <= 1:
return False
if num <= 3:
return True
if num % 2 == 0 or num % 3 == 0:
return False
i = 5
while i * i <= num:
if num % i == 0 or num % (i + 2) == 0:
return False
... | from solution import count_prime_product_subsets, is_prime
def test_is_prime_function():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(17) == True
assert is_prime(18) == False
def test_example_case():
primes = [2, 3, 5, 7, 11]
assert coun... | [
{
"docstring": "Helper function to check if a number is prime.",
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "Function to count subsets whose product is also a prime number.",
"function_declaration": "def count_pr... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005484_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(num):\n \"\"\"Helper function to check if a number is prime.\"\"\"\n if num <= 1:\n return False\n if num <= 3:\n return T... | trial_gpt4o_0 | {
"original_instruction": "Alice has a collection of unique prime numbers and she loves to create different subsets of these primes. Given a list of prime numbers, she wants to know how many subsets of these primes have a product that is also a prime number. She needs your help to find out.\n\nA prime number is a nat... | 0.694676 | Codeforces_20161 | C | [
"is_prime",
"count_prime_product_subsets"
] | 2 | [
[
"count_prime_product_subsets",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0e43a8ade13144d9fd827f394d1b352a13f3fdc5 | 673489b7b5941662459638ecde016e9f69306b9b | |||
v1.0 | complete | Codeforces | Codeforces_20244_C | from typing import List, Tuple
def solve_knapsack(input_data: str) -> int:
"""
Solve the knapsack problem given an input string.
Args:
input_data (str): A string containing the number of items, maximum weight capacity of the backpack,
and each item's weight and value.
Re... | def knapsack(n, W, items):
"""
Returns the maximum total value of items that can be put in a knapsack of capacity W.
:param n: Number of items
:param W: Maximum weight capacity of the knapsack
:param items: List of (weight, value) tuples
:return: Maximum value that can be achieved
"""
... | from solution import solve_knapsack
def test_example_case():
input_data = "3 50\n10 60\n20 100\n30 120"
assert solve_knapsack(input_data) == 220
def test_case_with_zero_values():
input_data = "3 50\n10 0\n20 0\n30 0"
assert solve_knapsack(input_data) == 0
def test_case_with_high_value_low_weight():
... | [
{
"docstring": "Returns the maximum total value of items that can be put in a knapsack of capacity W.\n\n:param n: Number of items\n:param W: Maximum weight capacity of the knapsack\n:param items: List of (weight, value) tuples\n:return: Maximum value that can be achieved",
"function_declaration": "def knap... | [
0,
0,
0,
0,
0,
0,
0,
0,
1,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005484_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def knapsack(n, W, items):\n \"\"\"\n Returns the maximum value that can be achieved with a given weight capacity.\n :param n: int - Number of items\... | trial_gpt4o_8 | {
"original_instruction": "Alex is preparing for a mission to Mars and needs to efficiently pack his backpack with supplies. The backpack has a maximum weight capacity of W. Alex has n types of items, each with a specific weight and value. He wants to maximize the total value of the items in his backpack without exce... | 0.536675 | Codeforces_20244 | C | [
"knapsack",
"parse_input",
"solve_knapsack"
] | 3 | [
[
"solve_knapsack",
"knapsack"
],
[
"solve_knapsack",
"parse_input"
]
] | 2 | [
"parse_input"
] | false | [] | false | pytest | true | [] | true | 41ed4227361db996859940f88e55249ea3d7a6a9 | 11b365e4c297d3460f717ac41ea9d2ed0b4576fc | |||
v1.0 | complete | Codeforces | Codeforces_20118_C | def minimum_cost_to_connect_towns(n: int, roads: List[Tuple[int, int, int]]) -> int:
""" Calculate the minimum possible cost to make the road network connected with the given towns and roads.
Args:
n (int): The number of towns.
roads (List[Tuple[int, int, int]]): A list of tuples where each tuple c... | def find(parent, i):
if parent[i] == i:
return i
else:
parent[i] = find(parent, parent[i])
return parent[i]
def union(parent, rank, x, y):
rootX = find(parent, x)
rootY = find(parent, y)
if rootX != rootY:
if rank[rootX] > rank[rootY]:
parent[rootY] = roo... | from solution import minimum_cost_to_connect_towns
def test_example1():
n = 4
roads = [(1, 2, 3), (2, 3, 4), (3, 4, 5)]
assert minimum_cost_to_connect_towns(n, roads) == 12
def test_example2():
n = 2
roads = [(1, 2, 1)]
assert minimum_cost_to_connect_towns(n, roads) == 1
def test_example3():
... | [
{
"docstring": null,
"function_declaration": "def find(parent, i):",
"function_name": "find",
"parameter_list": "(parent, i)"
},
{
"docstring": null,
"function_declaration": "def union(parent, rank, x, y):",
"function_name": "union",
"parameter_list": "(parent, rank, x, y)"
},
... | [
0,
0,
0,
1,
1
] | 2 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005484_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def minimum_road_construction_cost(n, m, roads):\n \"\"\"\n Returns the minimum total cost to make the road network connected.\n If it is impossible ... | trial_gpt4o_3 | {
"original_instruction": "A local government wants to improve its road infrastructure to minimize travel costs between towns. There are `n` towns and `m` bidirectional roads connecting some pairs of towns, with each road having an associated cost. The government plans to construct new roads to ensure that every town... | 0.680787 | Codeforces_20118 | C | [
"find",
"union",
"minimum_cost_to_connect_towns"
] | 3 | [
[
"minimum_cost_to_connect_towns",
"find"
],
[
"minimum_cost_to_connect_towns",
"union"
],
[
"union",
"find"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 38818b5750830236c7c8d4cb0645e76f7b940c76 | 822729be85ecb0294343b6cf515629acada33969 | |||
v1.0 | complete | Codeforces | Codeforces_20186_C | from typing import List
def largest_rectangle_area(grid: List[List[int]]) -> int:
"""
This function takes a 2D list of integers representing building heights and returns
the largest rectangular area where every building within the rectangle has the same height.
Args:
grid (List[List[int]]): A... | def largest_rectangle_area(grid):
"""
This function takes a 2D list of integers representing building heights and returns
the largest rectangular area where every building within the rectangle has the same height.
"""
if not grid:
return 0
n, m = len(grid), len(grid[0])
max_area = 0... | from solution import largest_rectangle_area
def test_largest_rectangle_area():
grid = [
[1, 1, 1, 0, 0],
[1, 1, 1, 0, 0],
[1, 1, 1, 0, 0],
[0, 0, 0, 0, 0]
]
assert largest_rectangle_area(grid) == 9
def test_single_cell_grid():
grid = [
[1]
]
assert l... | [
{
"docstring": "This function takes a 2D list of integers representing building heights and returns\nthe largest rectangular area where every building within the rectangle has the same height.",
"function_declaration": "def largest_rectangle_area(grid):",
"function_name": "largest_rectangle_area",
"... | [
0,
0,
0,
0,
0,
0,
0,
1,
0,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005484_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def maximalRectangle(matrix):\n if not matrix:\n return 0\n n, m = len(matrix), len(matrix[0])\n max_area = 0\n heights = [0] * m\n \n ... | trial_gpt4o_7 | {
"original_instruction": "You are given a city grid of size n x m where each cell in the grid represents a building which has a certain height. Your task is to identify the largest rectangular area in the grid where every cell within the rectangle has the same height.\n\nThe input consists of:\n- The first line cont... | 0.720414 | Codeforces_20186 | C | [
"largest_rectangle_area",
"max_histogram_area"
] | 2 | [
[
"largest_rectangle_area",
"max_histogram_area"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | cf8d118f46cd2940170aa5d943697e662e9524fa | 8ca9e9dfdf6103513e9f58ff692ffbcb4efab199 | |||
v1.0 | complete | Codeforces | Codeforces_20188_C | from typing import List, Tuple
def shortest_path_length(n: int, edges: List[Tuple[int, int]], queries: List[Tuple[int, int]]) -> List[int]:
"""
Determine the shortest path length between given pairs of nodes in a binary tree rooted at node 1.
Args:
n (int): Number of nodes in the tree.
edges ... | from collections import defaultdict, deque
def build_tree(n, edges):
tree = defaultdict(list)
for u, v in edges:
tree[u].append(v)
tree[v].append(u)
return tree
def bfs_distance(tree, start):
distances = {start: 0}
queue = deque([start])
while queue:
node = queue.poplef... | from solution import shortest_path_length
def test_example_case():
n = 5
edges = [(1, 2), (1, 3), (2, 4), (2, 5)]
queries = [(4, 5), (4, 3), (3, 5)]
assert shortest_path_length(n, edges, queries) == [2, 3, 3]
def test_chain_tree():
n = 4
edges = [(1, 2), (2, 3), (3, 4)]
queries = [(1, 4), ... | [
{
"docstring": null,
"function_declaration": "def build_tree(n, edges):",
"function_name": "build_tree",
"parameter_list": "(n, edges)"
},
{
"docstring": null,
"function_declaration": "def bfs_distance(tree, start):",
"function_name": "bfs_distance",
"parameter_list": "(tree, sta... | [
0,
0,
0,
0,
0,
1,
0,
1,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005484_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import defaultdict, deque\n\ndef shortest_path(n, edges, queries):\n # Build the tree as an adjacency list\n tree = defaultdict(list)\n... | trial_gpt4o_7 | {
"original_instruction": "You are given a binary tree rooted at node containing the integer value $$$1$$$. Each node in the binary tree contains a unique integer value. \n\nYour task is to determine the shortest path between any two given nodes in the tree. The path length between two nodes is defined as the number ... | 0.611049 | Codeforces_20188 | C | [
"build_tree",
"bfs_distance",
"shortest_path_length"
] | 3 | [
[
"shortest_path_length",
"bfs_distance"
],
[
"shortest_path_length",
"build_tree"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 71da682ec0f5664f11ae184e3c83adf45fdd85f6 | 020e51ba5aeb443944e16b239086f85218d4c372 | |||
v1.0 | complete | Codeforces | Codeforces_20284_C | def can_be_sorted_by_removing_one_element(t: int, test_cases: List[Tuple[int, List[int]]]) -> List[str]:
""" Given an array of integers, determine if it is possible to make the array sorted in non-decreasing
order by removing at most one element. For each test case, return "YES" if it's possible, otherwise "NO"... | def can_be_sorted_by_removing_one_element(t, test_cases):
results = []
for case in test_cases:
n, arr = case
if is_sorted(arr):
results.append("YES")
continue
found_solution = False
for i in range(n):
new_arr = arr[:i] + arr[i+1:]
... | def test_can_be_sorted_by_removing_one_element():
test_cases = [
(5, [1, 2, 10, 5, 7]),
(4, [1, 2, 3, 4]),
(6, [10, 5, 1, 3, 4, 6])
]
t = len(test_cases)
result = can_be_sorted_by_removing_one_element(t, test_cases)
assert result == ["YES", "YES", "NO"]
def test_can_be_sorte... | [
{
"docstring": null,
"function_declaration": "def can_be_sorted_by_removing_one_element(t, test_cases):",
"function_name": "can_be_sorted_by_removing_one_element",
"parameter_list": "(t, test_cases)"
},
{
"docstring": null,
"function_declaration": "def is_sorted(arr):",
"function_nam... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005484_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def can_be_sorted_by_removing_one_element(arr):\n n = len(arr)\n\n def is_sorted(array):\n return all(array[i] <= array[i + 1] for i in range(len... | trial_gpt4o_1 | {
"original_instruction": "Given an array of integers, you must determine whether you can make the array sorted in non-decreasing order by removing exactly one or zero elements. In other words, you need to check if it's possible to achieve a sorted array after removing at most one element from the array.\n\nThe input... | 0.669342 | Codeforces_20284 | C | [
"can_be_sorted_by_removing_one_element",
"is_sorted"
] | 2 | [
[
"can_be_sorted_by_removing_one_element",
"is_sorted"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 5c61ddffd5b1b70ad278e87ab24b77805f1c7dab | 31816b3b5de9c4953f32d26b513e96e91a1ceafd | |||
v1.0 | complete | Codeforces | Codeforces_20194_C | def preprocess_grid(grid):
"""
Preprocess the grid to create a prefix sum matrix for quick area sum lookup.
"""
def subgrid_sum(prefix_sum, r1, c1, r2, c2):
"""
Calculate the sum of the subgrid using the prefix sum matrix.
"""
def solve(n, q, grid, queries):
"""
Process each query and ... | def preprocess_grid(grid):
"""
Preprocess the grid to create a prefix sum matrix for quick area sum lookup.
"""
n = len(grid)
prefix_sum = [[0] * (n + 1) for _ in range(n + 1)]
for i in range(1, n + 1):
for j in range(1, n + 1):
prefix_sum[i][j] = grid[i-1][j-1] + prefix... | from solution import solve
def test_example_case():
n = 3
q = 2
grid = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
queries = [
(1, 1, 2, 2),
(2, 2, 3, 3)
]
expected = [12, 28]
assert solve(n, q, grid, queries) == expected
def test_single_element_subgrid(... | [
{
"docstring": "Preprocess the grid to create a prefix sum matrix for quick area sum lookup.",
"function_declaration": "def preprocess_grid(grid):",
"function_name": "preprocess_grid",
"parameter_list": "(grid)"
},
{
"docstring": "Calculate the sum of the subgrid using the prefix sum matrix.... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005484_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def preprocess_grid(grid):\n n = len(grid)\n prefix_sum = [[0] * (n + 1) for _ in range(n + 1)]\n for i in range(1, n + 1):\n for j in range(1... | trial_gpt4o_2 | {
"original_instruction": "You are given a grid with n rows and n columns, and each cell contains an integer value. The task is to answer multiple queries, each asking for the sum of elements in a subgrid defined by a given set of boundaries.\n\nSpecifically, each query specifies a rectangular subgrid by the top-left... | 0.560444 | Codeforces_20194 | C | [
"preprocess_grid",
"subgrid_sum",
"solve"
] | 3 | [
[
"solve",
"preprocess_grid"
],
[
"solve",
"subgrid_sum"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | dde8cc90b3cf41bd76b31d1bb573acbe937ce27f | d858897ce3e60014e7f8900bf4d9f2a5abbf6943 | |||
v1.0 | complete | Codeforces | Codeforces_20450_C | def chisels_solution(input_str: str) -> str:
"""
Determine if it's possible to create exactly k slots on the block using the given chisels such that
the sum of the widths of these k slots is equal to a given target value, T.
>>> chisels_solution("5 3 100\n30 20 25 50 70")
"YES\n1 2 3"
>>> ... | from itertools import combinations
def find_slots(n, k, T, chisels):
"""
Determine if it's possible to select k chisels such that the sum of their widths equals T.
:param n: Number of chisels
:param k: Required number of slots
:param T: Target width
:param chisels: List of chisels' widths
:... | from solution import chisels_solution
def test_chisels_solution_example():
input_str = "5 3 100\n30 20 25 50 70"
output_str = chisels_solution(input_str)
assert output_str.startswith("YES")
indices = list(map(int, output_str.split('\n')[1].split()))
chisels = [30, 20, 25, 50, 70]
assert len(ind... | [
{
"docstring": "Determine if it's possible to select k chisels such that the sum of their widths equals T.\n:param n: Number of chisels\n:param k: Required number of slots\n:param T: Target width\n:param chisels: List of chisels' widths\n:return: Tuple containing \"YES\" or \"NO\" and the indices of selected ch... | [
0,
0,
0,
0,
0,
0,
1,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005484_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from itertools import combinations\n\ndef carve_slots(n, k, T, chisels):\n for indices in combinations(range(n), k):\n if sum(chisels[i] for i in in... | trial_gpt4o_6 | {
"original_instruction": "You are given n chisels and a block of wood. The task is to carve out k slots on the block using the given chisels. Each chisel has a specific width and can create a slot of that width on the block. You are allowed to use each chisel at most once.\n\nYou need to determine if it is possible ... | 0.565177 | Codeforces_20450 | C | [
"find_slots",
"chisels_solution"
] | 2 | [
[
"chisels_solution",
"find_slots"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 643ff00c58ecb9d7afe9a0f1e23eec41fbe8a791 | d11e63efd1dae8bb0a0233402e73566a2edcb462 | |||
v1.0 | complete | Codeforces | Codeforces_20281_C | def process_operations(n, s, operations):
"""
Processes a list of operations on the string s.
Parameters:
n (int): The length of the string.
s (str): The initial string.
operations (list of str): The list of operations in the format described.
Returns:
list of str:... | def is_palindrome(s):
"""
Helper function to check if a given string s is a palindrome.
"""
return s == s[::-1]
def process_operations(n, s, operations):
"""
Processes a list of operations on the string s.
Parameters:
n (int): The length of the string.
s (str): The init... | from solution import process_operations
def test_example_case():
n = 5
s = "abcba"
operations = ["query 0 4", "replace 1 3 xyz", "query 0 4"]
result = process_operations(n, s, operations)
assert result == ["YES", "NO"]
def test_replace_only():
n = 3
s = "abc"
operations = ["replace 0 2... | [
{
"docstring": "Helper function to check if a given string s is a palindrome.",
"function_declaration": "def is_palindrome(s):",
"function_name": "is_palindrome",
"parameter_list": "(s)"
},
{
"docstring": "Processes a list of operations on the string s.\n\nParameters:\n n (int): The lengt... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005484_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def perform_operations(n, s, q, operations):\n result = []\n s = list(s) # Convert string to list for mutable operations\n\n for operation in operat... | trial_gpt4o_1 | {
"original_instruction": "John loves playing with strings. Recently, he came across a string consisting of lowercase Latin letters and decided to perform some operations on it. He has devised two types of operations that he can perform on this string:\n\n1. Replace a sub-string with another string of equal length.\n... | 0.583827 | Codeforces_20281 | C | [
"is_palindrome",
"process_operations"
] | 2 | [
[
"process_operations",
"is_palindrome"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 942cc57d296ddeba9efb0c490a9e02509b9eb9ac | ef5980193442304f41612342c97be2bc8764332e | |||
v1.0 | complete | Codeforces | Codeforces_20354_C | def minimum_toll(n: int, e: int, roads: List[Tuple[int, int, int]]) -> int:
""" Determine the minimum total toll cost required to ensure control over all castles.
If it is not possible to ensure control over all the castles, return -1.
>>> minimum_toll(4, 5, [(1, 2, 3), (2, 3, 4), (3, 4, 2), (1, 3, 5),... | def find(parent, i):
if parent[i] == i:
return i
else:
parent[i] = find(parent, parent[i])
return parent[i]
def union(parent, rank, x, y):
root_x = find(parent, x)
root_y = find(parent, y)
if root_x != root_y:
if rank[root_x] > rank[root_y]:
parent[r... | from solution import minimum_toll
def test_example_case():
n = 4
e = 5
roads = [
(1, 2, 3),
(2, 3, 4),
(3, 4, 2),
(1, 3, 5),
(1, 4, 8)
]
assert minimum_toll(n, e, roads) == 9
def test_single_castle():
assert minimum_toll(1, 0, []) == 0
def test_disconne... | [
{
"docstring": null,
"function_declaration": "def find(parent, i):",
"function_name": "find",
"parameter_list": "(parent, i)"
},
{
"docstring": null,
"function_declaration": "def union(parent, rank, x, y):",
"function_name": "union",
"parameter_list": "(parent, rank, x, y)"
},
... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005484_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def find(parent, i):\n if parent[i] == i:\n return i\n else:\n parent[i] = find(parent, parent[i])\n return parent[i]\n\ndef union(... | trial_gpt4o_0 | {
"original_instruction": "A medieval kingdom has a number of castles connected by bidirectional roads. Each road has a certain toll fee associated with it. The king wants to maintain control over all the castles while minimizing the total toll fees collected.\n\nYou are given an integer n, the number of castles, and... | 0.669211 | Codeforces_20354 | C | [
"find",
"union",
"kruskal_mst",
"minimum_toll"
] | 4 | [
[
"kruskal_mst",
"find"
],
[
"kruskal_mst",
"union"
],
[
"minimum_toll",
"kruskal_mst"
],
[
"union",
"find"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | fe9d56c8f4cdf1ba7116f006be3e3ede2c0042ab | f60e6277bea36b5e54c42b42a2cf5d39b16549d9 | |||
v1.0 | complete | Codeforces | Codeforces_20402_C | def longest_common_prefix_length(str1: str, str2: str) -> int:
""" Returns the length of the longest common prefix between str1 and str2.
>>> longest_common_prefix_length("apple", "ape") == 2
>>> longest_common_prefix_length("apple", "apricot") == 2
>>> longest_common_prefix_length("banana", "band") == ... | def longest_common_prefix_length(str1, str2):
"""
Returns the length of the longest common prefix between str1 and str2.
"""
common_length = 0
for a, b in zip(str1, str2):
if a == b:
common_length += 1
else:
break
return common_length
def max_common_prefi... | from solution import longest_common_prefix_length, max_common_prefix_length
def test_longest_common_prefix_length():
assert longest_common_prefix_length("apple", "ape") == 2
assert longest_common_prefix_length("apple", "apricot") == 2
assert longest_common_prefix_length("banana", "band") == 3
assert lo... | [
{
"docstring": "Returns the length of the longest common prefix between str1 and str2.",
"function_declaration": "def longest_common_prefix_length(str1, str2):",
"function_name": "longest_common_prefix_length",
"parameter_list": "(str1, str2)"
},
{
"docstring": "Returns the maximum length of... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005484_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def longest_common_prefix_length(messages):\n \"\"\"\n Given a list of messages, determines the maximum length of a common prefix shared\n by any two... | trial_gpt4o_2 | {
"original_instruction": "The kingdom of Lexocrypt is known for its large collection of ancient encrypted texts. Given a set of encrypted messages, each represented by a string of lowercase letters, the king's cryptanalysts have identified that certain messages share common prefix patterns. To further their research... | 0.759503 | Codeforces_20402 | C | [
"longest_common_prefix_length",
"max_common_prefix_length"
] | 2 | [
[
"max_common_prefix_length",
"longest_common_prefix_length"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 839c96276c76e4ae5c6c744cf6dd90383ab671bc | ebb314ee83d65dd58097e5e6b6e18dbdf1db43b3 | |||
v1.0 | complete | Codeforces | Codeforces_20485_C | def rotate_matrix(input_str: str) -> str:
""" Rotate a matrix 90 degrees clockwise.
The first line of the input contains two integers, n and m (1 ≤ n, m ≤ 100), which represent the number of rows and columns in the matrix, respectively.
The next n lines each contain m integers, representing the elemen... | def rotate_matrix_90_degrees_clockwise(matrix):
"""
Rotates the given matrix 90 degrees clockwise.
"""
n = len(matrix)
m = len(matrix[0])
rotated_matrix = [[0]*n for _ in range(m)]
for i in range(n):
for j in range(m):
rotated_matrix[j][n - 1 - i] = matrix[i][j]
... | from solution import rotate_matrix
def test_rotate_matrix_3x4():
input_str = "3 4\n1 2 3 4\n5 6 7 8\n9 10 11 12"
expected_output = "9 5 1\n10 6 2\n11 7 3\n12 8 4"
assert rotate_matrix(input_str) == expected_output
def test_rotate_matrix_2x2():
input_str = "2 2\n1 2\n3 4"
expected_output = "3 1\n4 ... | [
{
"docstring": "Rotates the given matrix 90 degrees clockwise.",
"function_declaration": "def rotate_matrix_90_degrees_clockwise(matrix):",
"function_name": "rotate_matrix_90_degrees_clockwise",
"parameter_list": "(matrix)"
},
{
"docstring": null,
"function_declaration": "def convert_inp... | [
1,
1
] | 2 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005484_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def rotate_matrix_90_degrees_clockwise(matrix):\n \"\"\"\n Rotates the given n x m matrix 90 degrees clockwise.\n \n :param matrix: List[List[int]... | trial_gpt4o_2 | {
"original_instruction": "You are given a matrix of integers with dimensions n x m. Your task is to rotate the matrix 90 degrees clockwise.\n\nThe first line of the input contains two integers, n and m (1 ≤ n, m ≤ 100), which represent the number of rows and columns in the matrix, respectively.\n\nThe next n lines e... | 0.601537 | Codeforces_20485 | C | [
"rotate_matrix_90_degrees_clockwise",
"convert_input_to_matrix",
"convert_matrix_to_output",
"rotate_matrix"
] | 4 | [
[
"rotate_matrix",
"convert_input_to_matrix"
],
[
"rotate_matrix",
"convert_matrix_to_output"
],
[
"rotate_matrix",
"rotate_matrix_90_degrees_clockwise"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | e6b1c4313c5071277564ec6fbade662bb42bf701 | 96125c1ceb456beb95665fdf7a03af7182e188c9 | |||
v1.0 | complete | Codeforces | Codeforces_20277_C | def bacteria_colony(m: int, n: int, k: int, initial_state: List[List[int]]) -> List[List[int]]:
"""
A colony of bacteria grows in a rectangular grid with dimensions m × n. Each cell in the grid can either be empty (denoted by 0) or contain a bacterium (denoted by 1). Over time, the bacteria spread to adjacent c... | def get_next_state(grid):
"""
Given the current state of the grid, compute the state for the next generation.
"""
m, n = len(grid), len(grid[0])
next_grid = [[0] * n for _ in range(m)]
def count_adjacent_bacteria(x, y):
directions = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, ... | from solution import bacteria_colony
def test_bacteria_colony_case1():
initial_state = [
[0, 1, 0, 0, 0],
[0, 0, 1, 0, 0],
[1, 1, 1, 0, 0],
[0, 0, 0, 0, 0]
]
m, n, k = 4, 5, 1
expected_state = [
[0, 0, 0, 0, 0],
[1, 0, 1, 0, 0],
[0, 1, 1, 0, 0],
... | [
{
"docstring": "Given the current state of the grid, compute the state for the next generation.",
"function_declaration": "def get_next_state(grid):",
"function_name": "get_next_state",
"parameter_list": "(grid)"
},
{
"docstring": null,
"function_declaration": "def bacteria_colony(m, n, ... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005484_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def update_grid(grid, m, n):\n def count_adjacent_bacteria(x, y):\n directions = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, ... | trial_gpt4o_1 | {
"original_instruction": "Colony of Bacteria\n\nA colony of bacteria grows in a rectangular grid with dimensions m × n. Each cell in the grid can either be empty (denoted by 0) or contain a bacterium (denoted by 1). Over time, the bacteria spread to adjacent cells according to the following rules:\n1. A bacterium in... | 0.597761 | Codeforces_20277 | C | [
"get_next_state",
"bacteria_colony",
"print_grid"
] | 3 | [
[
"bacteria_colony",
"get_next_state"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5c6c49c7e280f92f10c4fcb08c8fdc7add799e72 | e141539c4b1056ad8410ea4a78e757037c237b46 | |||
v1.0 | complete | Codeforces | Codeforces_20478_C | from typing import List, Tuple
from collections import deque
def get_farthest_node(start: int, adjacency_list: List[List[int]]) -> Tuple[int, int]:
"""
Perform BFS and return the farthest node and its distance from the start node.
"""
pass
def tree_diameter(n: int, edges: List[Tuple[int, int]]) -> int... | from collections import deque
def get_farthest_node(start, adjacency_list):
"""
Perform BFS and return the farthest node and its distance from the start node.
"""
n = len(adjacency_list)
visited = [False] * (n + 1)
queue = deque([(start, 0)])
visited[start] = True
farthest_node = start
... | def test_tree_diameter():
edges = [
(1, 2),
(1, 3),
(2, 4),
(2, 5),
(3, 6)
]
assert tree_diameter(6, edges) == 4
def test_small_tree():
edges = [
(1, 2)
]
assert tree_diameter(2, edges) == 1
def test_balanced_tree():
edges = [
(1, 2),... | [
{
"docstring": "Perform BFS and return the farthest node and its distance from the start node.",
"function_declaration": "def get_farthest_node(start, adjacency_list):",
"function_name": "get_farthest_node",
"parameter_list": "(start, adjacency_list)"
},
{
"docstring": "Given the number of n... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005484_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import deque\n\ndef get_farthest_node(start, adjacency_list):\n \"\"\"\n Perform BFS and return the farthest node and its distance from... | trial_gpt4o_0 | {
"original_instruction": "Consider a tree (an acyclic, connected graph) with \\( n \\) vertices labeled from \\( 1 \\) to \\( n \\). You are given the tree as an adjacency list in which each vertex contains a list of its directly connected vertices. Your task is to determine the diameter of the tree. The diameter is... | 0.643152 | Codeforces_20478 | C | [
"get_farthest_node",
"tree_diameter"
] | 2 | [
[
"tree_diameter",
"get_farthest_node"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | fd0f955d01dcbf9f2d4294bc397ab879238e2c80 | a91614be612b5428728ec8e4369ff5f7b8cb7c49 | |||
v1.0 | complete | Codeforces | Codeforces_20313_C | from typing import List, Tuple
def precompute_even_prefix_sums(arr: List[int]) -> List[int]:
"""
Precompute the prefix sums of even numbers in the given array.
"""
...
def query_even_sum(even_prefix_sums: List[int], l: int, r: int) -> int:
"""
Query the sum of even numbers in the segment of th... | def precompute_even_prefix_sums(arr):
n = len(arr)
even_prefix_sums = [0] * (n + 1) # initialize prefix sum array with an extra zero at the beginning
for i in range(1, n + 1):
even_prefix_sums[i] = even_prefix_sums[i - 1] + (arr[i - 1] if arr[i - 1] % 2 == 0 else 0)
return even_prefix_sums
def... | from solution import precompute_even_prefix_sums, query_even_sum, process_queries
def test_precompute_even_prefix_sums():
arr = [1, 2, 3, 4, 5, 6]
expected = [0, 0, 2, 2, 6, 6, 12]
assert precompute_even_prefix_sums(arr) == expected
def test_query_even_sum():
arr = [1, 2, 3, 4, 5, 6]
even_prefix_s... | [
{
"docstring": null,
"function_declaration": "def precompute_even_prefix_sums(arr):",
"function_name": "precompute_even_prefix_sums",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def query_even_sum(even_prefix_sums, l, r):",
"function_name": "query_even_... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005484_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def preprocess_even_sum(arr):\n \"\"\"\n Preprocess the given array to create a prefix sum array for even numbers.\n \n Parameters:\n arr (list... | trial_gpt4o_1 | {
"original_instruction": "You are given an array of integers and you need to answer multiple queries about it. Each query consists of two integers l and r, and you need to find the sum of all the even numbers in the segment of the array from index l to index r, inclusive (1-based indexing).\n\nThe array and queries ... | 0.636295 | Codeforces_20313 | C | [
"precompute_even_prefix_sums",
"query_even_sum",
"process_queries"
] | 3 | [
[
"process_queries",
"precompute_even_prefix_sums"
],
[
"process_queries",
"query_even_sum"
]
] | 2 | [
"process_queries"
] | false | [] | false | pytest | true | [] | true | 3cf65d0af0afc71319f022e446c29c261110ac85 | 034a043cdf6b0a1606f7d56a122e3c3b99193225 | |||
v1.0 | complete | Codeforces | Codeforces_20788_C | from collections import deque
from typing import List
def can_reach_and_return(n: int, m: int, grid: List[List[str]]) -> str:
""" Determine if it is possible to reach the bottom-right corner
and return to the top-left corner according to the rules.
>>> can_reach_and_return(3, 3, [['.', '.', '.'], ['.... | from collections import deque
def is_valid(x, y, n, m, grid, visited):
return 0 <= x < n and 0 <= y < m and grid[x][y] != '#' and visited[x][y] != 1
def bfs(n, m, grid, start, end):
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
queue = deque([(start, 0)])
visited = [[0] * m for _ in range(n)]
vi... | def test_simple_no_traps():
n = 3
m = 3
grid = [
[".", ".", "."],
[".", "#", "."],
[".", ".", "."]
]
assert can_reach_and_return(n, m, grid) == "YES"
def test_no_possible_path():
n = 3
m = 3
grid = [
[".", ".", "."],
["#", "#", "#"],
[".",... | [
{
"docstring": null,
"function_declaration": "def is_valid(x, y, n, m, grid, visited):",
"function_name": "is_valid",
"parameter_list": "(x, y, n, m, grid, visited)"
},
{
"docstring": null,
"function_declaration": "def bfs(n, m, grid, start, end):",
"function_name": "bfs",
"param... | [
0,
0,
0,
0,
1
] | 1 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005484_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import deque\n\ndef is_within_bounds(x, y, n, m):\n return 0 <= x < n and 0 <= y < m\n\ndef bfs(grid, n, m, start, end):\n directions =... | trial_gpt4o_4 | {
"original_instruction": "You are given a maze represented by an $n \\times m$ grid. Some of the cells are blocked and some are open. You start at the top-left corner of the maze and need to reach the bottom-right corner. You can move to an adjacent cell if it's open, in one of the four directions: up, down, left, o... | 0.602993 | Codeforces_20788 | C | [
"is_valid",
"bfs",
"can_reach_and_return",
"main"
] | 4 | [
[
"bfs",
"is_valid"
],
[
"can_reach_and_return",
"bfs"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | 79dd7dfc18ee35dc7c3c739db84496975ec736e1 | 6c6c37d7604449f4026100c6437e9bfd9b0e0b74 | |||
v1.0 | complete | Codeforces | Codeforces_20529_C | def hiking_trail(n: int, m: int, k: int, grid_lines: List[str]) -> Union[int, List[Tuple[int, int]]]:
""" Petya is organizing a hiking event and wants to create a unique hiking path for the participants.
The hiking trail is represented as a grid of size `n x m`. Each cell of the grid can be either land or water... | def find_continuous_trail(grid, n, m, k):
def is_valid(x, y):
return 0 <= x < n and 0 <= y < m and grid[x][y] == '.' and (x, y) not in visited
def dfs(x, y):
if len(path) == k:
return True
visited.add((x, y))
path.append((x, y))
for dx, dy in [(-1, 0), (1, 0)... | def test_hiking_trail_easy():
n = 5
m = 5
k = 8
grid_lines = [
".#...",
"...#.",
"..##.",
".#..#",
"....."
]
result = hiking_trail(n, m, k, grid_lines)
assert result != -1
assert len(result) == k
def test_hiking_trail_no_continuous_path():
n =... | [
{
"docstring": null,
"function_declaration": "def find_continuous_trail(grid, n, m, k):",
"function_name": "find_continuous_trail",
"parameter_list": "(grid, n, m, k)"
},
{
"docstring": null,
"function_declaration": "def hiking_trail(n, m, k, grid_lines):",
"function_name": "hiking_t... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005484_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def find_hiking_trail(n, m, k, grid):\n directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]\n\n def is_valid(x, y):\n return 0 <= x < n and 0 <= y < ... | trial_gpt4o_2 | {
"original_instruction": "Petya is organizing a hiking event and wants to create a unique hiking path for the participants. The hiking trail is represented as a grid of size `n x m`. Each cell of the grid can be either land or water. The trail can only be built on land, and hikers can move between adjacent cells (le... | 0.623463 | Codeforces_20529 | C | [
"find_continuous_trail",
"hiking_trail"
] | 2 | [
[
"hiking_trail",
"find_continuous_trail"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | a83f63d5501c661e39261f61cad5d8c058669d08 | 66e603423f0e4e73717a1877a29bedf283b6b0ea | |||
v1.0 | complete | Codeforces | Codeforces_20208_C | from typing import List, Tuple
def perform_swaps(grid: List[List[int]], operations: List[Tuple[int, int, int, int]]) -> List[List[int]]:
"""
Perform the given swap operations on the grid and return the final state of the grid.
:param grid: List of lists representing the initial state of the grid.
:par... | def perform_swaps(grid, operations):
"""
Perform the given swap operations on the grid and return the final state of the grid.
:param grid: List of lists representing the initial state of the grid.
:param operations: List of tuples representing swap operations.
:return: List of lists representing t... | def test_sample_case():
m, n, k = 3, 3, 2
grid = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
operations = [
(1, 1, 3, 3),
(2, 2, 3, 1)
]
expected_output = [
[9, 2, 3],
[4, 7, 6],
[5, 8, 1]
]
assert read_input_and_process_operations(... | [
{
"docstring": "Perform the given swap operations on the grid and return the final state of the grid.\n\n:param grid: List of lists representing the initial state of the grid.\n:param operations: List of tuples representing swap operations.\n:return: List of lists representing the final state of the grid after ... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005484_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def perform_swaps(grid, operations):\n \"\"\"\n Perform the given swap operations on the grid and return the final state of the grid.\n\n :param grid... | trial_gpt4o_0 | {
"original_instruction": "Nicole is a graphic designer who frequently works with grids of pixels. She wants to create a mosaic, which is an m x n grid, where each cell contains an integer representing a color.\n\nGiven the grid and a sequence of swap operations, where each operation consists of swapping the content ... | 0.679101 | Codeforces_20208 | C | [
"perform_swaps",
"read_input_and_process_operations"
] | 2 | [
[
"read_input_and_process_operations",
"perform_swaps"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 58714acb72dcf10abe319bae0b0a0e4518cd6be0 | e28968ba015f9f1b33bf3b583bae1f1148134eb6 | |||
v1.0 | complete | Codeforces | Codeforces_20933_C | def min_swaps_to_sort(arr: List[int]) -> int:
"""
Returns the minimum number of swaps required to sort the array in non-decreasing order.
Args:
arr (list): The list of integers to sort.
Returns:
int: The minimum number of swaps.
>>> min_swaps_to_sort([4, 3, 2, 1])
6
>>> min_sw... | def count_inversions(arr):
"""
Counts the number of inversions in the array using a modified merge sort.
Args:
arr (list): The list of integers to count inversions in.
Returns:
int: The number of inversions needed to sort the array.
"""
def merge_count_split_inv(arr, temp_arr, ... | from solution import min_swaps_to_sort
def test_min_swaps_to_sort_example_1():
assert min_swaps_to_sort([4, 3, 2, 1]) == 6
def test_min_swaps_to_sort_sorted_array():
assert min_swaps_to_sort([1, 2, 3, 4]) == 0
def test_min_swaps_to_sort_reverse_sorted_array():
assert min_swaps_to_sort([4, 3, 2, 1]) == 6
... | [
{
"docstring": "Counts the number of inversions in the array using a modified merge sort.\n\nArgs:\narr (list): The list of integers to count inversions in.\n\nReturns:\nint: The number of inversions needed to sort the array.",
"function_declaration": "def count_inversions(arr):",
"function_name": "coun... | [
0,
0,
0,
0,
0,
0,
0,
0,
1,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005484_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def minimum_swaps_to_sort(arr):\n \"\"\"\n Counts the minimum number of swaps required to sort the array using adjacent swaps only.\n \"\"\"\n # C... | trial_gpt4o_8 | {
"original_instruction": "Alice loves playing with numbers. She is given an array of integers, and she can perform the following operation any number of times (including zero):\n\n- Pick any two adjacent elements of the array and swap them.\n\nAlice wants to know the minimum number of swaps required to sort the arra... | 0.63016 | Codeforces_20933 | C | [
"count_inversions",
"min_swaps_to_sort"
] | 2 | [
[
"min_swaps_to_sort",
"count_inversions"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2ae9d36e9d62ab6d878ea10345228446188aed62 | 4f61c299aacef9ff62314f36ff15c2f1b05288a1 | |||
v1.0 | complete | Codeforces | Codeforces_20705_C | from typing import List
def get_combinations_string(n: int, budget: int, costs: List[int]) -> List[str]:
"""You are given an array of integers representing the costs of different items in a shop.
You have a certain budget and you want to buy a combination of these items such that the total cost is exactly equ... | from itertools import combinations
def find_combinations(costs, budget):
"""
Finds all distinct combinations of items that sum up to the given budget.
"""
costs.sort()
result = []
n = len(costs)
def backtrack(start, current_combo, current_sum):
if current_sum == budget:
... | from solution import get_combinations_string
def test_with_example_1():
assert get_combinations_string(4, 7, [2, 3, 6, 7]) == ["7"]
def test_with_example_2():
assert get_combinations_string(5, 8, [2, 4, 1, 7, 6]) == ["1 7", "2 6"]
def test_no_solution():
assert get_combinations_string(3, 15, [2, 3, 4]) =... | [
{
"docstring": "Finds all distinct combinations of items that sum up to the given budget.",
"function_declaration": "def find_combinations(costs, budget):",
"function_name": "find_combinations",
"parameter_list": "(costs, budget)"
},
{
"docstring": null,
"function_declaration": "def get_... | [
0,
0,
0,
0,
1
] | 1 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005484_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef find_combinations(items: List[int], budget: int) -> List[List[int]]:\n \"\"\"\n Finds all distinct combinations of items ... | trial_gpt4o_4 | {
"original_instruction": "You are given an array of integers representing the costs of different items in a shop. You have a certain budget and you want to buy a combination of these items such that the total cost is exactly equal to your budget. You can only buy each item once.\n\nWrite a function that returns all ... | 0.666938 | Codeforces_20705 | C | [
"find_combinations",
"get_combinations_string"
] | 2 | [
[
"get_combinations_string",
"find_combinations"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 07b7d6e8ad0267705d800527d948c6a6897471b9 | e6d1cffd1f87f04eab6587588d81b6686e42c4dc | |||
v1.0 | complete | Codeforces | Codeforces_20691_C | from typing import List
def gcd(a: int, b: int) -> int:
"""Helper function to compute the greatest common divisor of a and b."""
while b:
a, b = b, a % b
return a
def longest_subsequence_with_common_divisor(n: int, activity_levels: List[int]) -> int:
"""Returns the length of the longest subseq... | def gcd(a, b):
"""Helper function to compute the greatest common divisor of a and b."""
while b:
a, b = b, a % b
return a
def longest_subsequence_with_common_divisor(n, activity_levels):
"""Returns the length of the longest subsequence where any two consecutive activity levels have a common div... | def test_gcd_basic():
assert gcd(10, 20) == 10
assert gcd(14, 25) == 1
assert gcd(49, 30) == 1
assert gcd(25, 30) == 5
def test_single_record():
assert longest_subsequence_with_common_divisor(1, [10]) == 1
assert longest_subsequence_with_common_divisor(1, [25]) == 1
def test_example_case():
... | [
{
"docstring": "Helper function to compute the greatest common divisor of a and b.",
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Returns the length of the longest subsequence where any two consecutive activity levels have a ... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005484_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def gcd(a, b):\n \"\"\"Helper function to compute the greatest common divisor of a and b.\"\"\"\n while b:\n a, b = b, a % b\n return a\n\ndef... | trial_gpt4o_0 | {
"original_instruction": "The Code Eaters Software company recently started a project to analyze user data. They have a dataset consisting of n records, each record containing an integer denoting user activity level for a particular day. The company's goal is to identify the longest subsequence of records where any ... | 0.66007 | Codeforces_20691 | C | [
"gcd",
"longest_subsequence_with_common_divisor"
] | 2 | [
[
"longest_subsequence_with_common_divisor",
"gcd"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 8ae730d9482c539ba00b4c0759b449958d5ef000 | 7652e7c8dd6b2e768034ef24ecd9fb75dfa7d0b8 | |||
v1.0 | complete | Codeforces | Codeforces_20555_C | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def build_tree(level_order_values):
"""Builds a binary tree from the given level order traversal values."""
if not level_order_values or level_order_values[0] == -1:
... | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def build_tree(level_order_values):
if not level_order_values or level_order_values[0] == -1:
return None
iterator = iter(level_order_values)
root = ... | from solution import pre_order_from_level_order
def test_basic_tree():
level_order = [1, 2, 3, 4, 5, -1, -1, -1, -1, 6, 7]
assert pre_order_from_level_order(level_order) == [1, 2, 4, 5, 6, 7, 3]
def test_single_node():
level_order = [1]
assert pre_order_from_level_order(level_order) == [1]
def test_n... | [] | [
1,
1
] | 2 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005484_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\ndef build_tree_level_order(arr):\n ... | trial_gpt4o_1 | {
"original_instruction": "Alex has just started learning about trees and binary tree traversal algorithms. A binary tree is a tree data structure in which each node has at most two children, referred to as the left child and the right child. He is studying pre-order traversal, in which the nodes are recursively visi... | 0.530017 | Codeforces_20555 | C | [
"build_tree",
"pre_order_traversal",
"pre_order_from_level_order"
] | 3 | [
[
"pre_order_from_level_order",
"build_tree"
],
[
"pre_order_from_level_order",
"pre_order_traversal"
]
] | 2 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 70e6ed5a996d426038670127044eff3114a9299f | 6913d7c9595363a06b4481f494085d8b1d2ccfa0 | |||
v1.0 | complete | Codeforces | Codeforces_20893_C | def minimum_transport_fee(N: int, edge_connections: List[Tuple[int, int, int]], queries: List[Tuple[int, int]]) -> List[int]:
""" Given the city's tree structure and the lengths of the roads,
for each query, determine the minimum transport fee to travel between two specified districts.
>>> minimum_transpor... | from collections import defaultdict, deque
import sys
input = sys.stdin.read
sys.setrecursionlimit(200000)
def find_LCA_and_minimum_edge(parent, lca_matrix, min_edge_matrix, depth, u, v):
if depth[u] < depth[v]:
u, v = v, u
diff = depth[u] - depth[v]
min_edge = float('inf')
for i in range(17)... | def test_minimum_transport_fee():
result = minimum_transport_fee(
5,
[(1, 2, 3), (1, 3, 2), (3, 4, 4), (3, 5, 1)],
[(4, 5), (1, 4), (2, 5)]
)
assert result == [1, 2, 1]
def test_minimum_transport_fee_single_query():
result = minimum_transport_fee(
5,
[(1, 2, 3), ... | [
{
"docstring": null,
"function_declaration": "def find_LCA_and_minimum_edge(parent, lca_matrix, min_edge_matrix, depth, u, v):",
"function_name": "find_LCA_and_minimum_edge",
"parameter_list": "(parent, lca_matrix, min_edge_matrix, depth, u, v)"
},
{
"docstring": null,
"function_declarat... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005484_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def find_lca_and_min_edge(u, v, n, parent, depth, min_edge):\n if depth[u] < depth[v]:\n u, v = v, u\n diff = depth[u] - depth[v]\n min_cost =... | trial_gpt4o_1 | {
"original_instruction": "In a fictional city, there is a unique system of roads connecting several districts. The roads form a tree structure, meaning that there is exactly one path between any two districts. Each road has a certain length.\n\nThe mayor decided to launch a new public transportation service called \... | 0.692542 | Codeforces_20893 | C | [
"find_LCA_and_minimum_edge",
"preprocess_lca",
"minimum_transport_fee"
] | 3 | [
[
"minimum_transport_fee",
"find_LCA_and_minimum_edge"
],
[
"minimum_transport_fee",
"preprocess_lca"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | 7f70ec35d756abdea79614c1396d18dfcc2a6a39 | 600d4054b3a650f5d288047555436a55216920f4 | |||
v1.0 | complete | Codeforces | Codeforces_21055_C | from typing import List
def is_valid_password(password: str) -> str:
"""
Check if a password is valid based on predefined criteria.
>>> is_valid_password("aB1")
'Valid'
>>> is_valid_password("abcdefgh")
'Invalid'
>>> is_valid_password("ABCDEFGH")
'Invalid'
>>> is_valid_password("123... | def is_valid_password(password):
"""
Check if a password is valid based on predefined criteria.
"""
if len(password) < 1 or len(password) > 100:
return "Invalid"
has_upper = False
has_lower = False
has_digit = False
for char in password:
if char.isupper():
... | from solution import is_valid_password, validate_passwords
def test_is_valid_password():
assert is_valid_password("aB1") == "Valid"
assert is_valid_password("abcdefgh") == "Invalid"
assert is_valid_password("ABCDEFGH") == "Invalid"
assert is_valid_password("12345678") == "Invalid"
assert is_valid_p... | [
{
"docstring": "Check if a password is valid based on predefined criteria.",
"function_declaration": "def is_valid_password(password):",
"function_name": "is_valid_password",
"parameter_list": "(password)"
},
{
"docstring": "Given a list of passwords, determine which are valid.",
"functi... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005484_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import re\n\ndef is_valid_password(password):\n \"\"\"\n Checks if the given password meets all the criteria:\n 1. The password must be of length 1 t... | trial_gpt4o_2 | {
"original_instruction": "Samuel enjoys creating unique passwords. He recently read about a method where a password should be considered \"valid\" if it meets certain criteria based on its length and the type of characters it contains.\n\nSamuel decides to follow these rules:\n1. The password must be of length n (1 ... | 0.595764 | Codeforces_21055 | C | [
"is_valid_password",
"validate_passwords"
] | 2 | [
[
"validate_passwords",
"is_valid_password"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1abdd67e651094febc8044aef7771b297786f93f | 3efe5fb39f586145cbc3be7404d790d9f711254b | |||
v1.0 | complete | Codeforces | Codeforces_21141_C | def sieve_of_eratosthenes(limit):
"""
Generate a list of prime numbers up to the given limit using the Sieve of Eratosthenes algorithm.
>>> sieve_of_eratosthenes(10)
[2, 3, 5, 7]
>>> sieve_of_eratosthenes(20)
[2, 3, 5, 7, 11, 13, 17, 19]
"""
pass
def distinct_prime_factors_sum(num... | def sieve_of_eratosthenes(limit):
primes = []
is_prime = [True] * (limit + 1)
is_prime[0] = is_prime[1] = False
for num in range(2, limit + 1):
if is_prime[num]:
primes.append(num)
for multiple in range(num * num, limit + 1, num):
is_prime[multiple] =... | def test_sieve_of_eratosthenes():
assert sieve_of_eratosthenes(10) == [2, 3, 5, 7]
assert sieve_of_eratosthenes(20) == [2, 3, 5, 7, 11, 13, 17, 19]
def test_distinct_prime_factors_sum():
primes = sieve_of_eratosthenes(100)
assert distinct_prime_factors_sum(18, primes) == 5 # Factors: 2, 3
assert d... | [
{
"docstring": null,
"function_declaration": "def sieve_of_eratosthenes(limit):",
"function_name": "sieve_of_eratosthenes",
"parameter_list": "(limit)"
},
{
"docstring": null,
"function_declaration": "def distinct_prime_factors_sum(number, primes):",
"function_name": "distinct_prime_... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005484_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from sympy import primefactors\n\ndef smallest_integer_with_smallest_sdp_fast(n, numbers):\n \"\"\"\n Returns the smallest integer with the smallest Sum... | trial_gpt4o_1 | {
"original_instruction": "Thom is fascinated by prime numbers and recently stumbled upon an interesting concept: the Sum of Distinct Prime Factors (SDPF) of a number. The SDPF of a number is calculated by summing all its distinct prime factors. For example, the SDPF of 18 is 2 + 3 = 5, because 2 and 3 are the distin... | 0.637994 | Codeforces_21141 | C | [
"sieve_of_eratosthenes",
"distinct_prime_factors_sum",
"smallest_integer_with_smallest_sdpfs"
] | 3 | [
[
"smallest_integer_with_smallest_sdpfs",
"distinct_prime_factors_sum"
],
[
"smallest_integer_with_smallest_sdpfs",
"sieve_of_eratosthenes"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | d674c899c4a622de0c933b0d318886368e6b552d | 75852ba6c7cd576af1a72645c6699e1c21ba5530 | |||
v1.0 | complete | Codeforces | Codeforces_20756_C | def can_redistribute_books(n: int, k: int, books: List[int]) -> bool:
"""
Determines if it's possible to redistribute books so that no compartment exceeds the threshold k
:param n: The number of compartments
:param k: The maximum allowed number of books per compartment
:param books: A list of intege... | def can_redistribute_books(n, k, books):
"""
Determines if it's possible to redistribute books so that no compartment exceeds the threshold k
"""
total_books = sum(books)
max_possible_books_in_compartment = (total_books + n - 1) // n
return max_possible_books_in_compartment <= k
def solution():... | def test_can_redistribute_books_yes():
assert can_redistribute_books(5, 5, [3, 8, 6, 2, 4]) == True
assert can_redistribute_books(4, 4, [4, 4, 4, 4]) == True
assert can_redistribute_books(3, 10, [3, 3, 3]) == True
def test_can_redistribute_books_no():
assert can_redistribute_books(3, 2, [3, 1, 5]) == F... | [
{
"docstring": "Determines if it's possible to redistribute books so that no compartment exceeds the threshold k",
"function_declaration": "def can_redistribute_books(n, k, books):",
"function_name": "can_redistribute_books",
"parameter_list": "(n, k, books)"
},
{
"docstring": null,
"fun... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005484_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def can_redistribute_books(n, k, book_counts):\n \"\"\"\n Determines if it's possible to redistribute the books so that no compartment has more than k b... | trial_gpt4o_2 | {
"original_instruction": "Daria has a bookshelf with n compartments, and each compartment contains a certain number of books. She likes keeping her bookshelf organized, so she wants to ensure that the number of books in each compartment doesn't exceed a certain threshold k.\n\nTo achieve this, Daria can perform a se... | 0.635166 | Codeforces_20756 | C | [
"can_redistribute_books",
"solution"
] | 2 | [
[
"solution",
"can_redistribute_books"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | c659267a6cfeeb940966b0edeb810c93cc42733a | a0501bc3fdafd010886c43ead31e51d56a101140 | |||
v1.0 | complete | Codeforces | Codeforces_21058_C | def calculate_car(ratings):
"""
Calculate the Critical Average Rating (CAR) for a list of ratings.
Args:
ratings (list): List of integers representing the ratings.
Returns:
float: The CAR value rounded to two decimal places.
"""
pass
def process_products(products):
"""
... | def calculate_car(ratings):
"""
Calculate the Critical Average Rating (CAR) for a list of ratings.
Args:
ratings (list): List of integers representing the ratings.
Returns:
float: The CAR value rounded to two decimal places.
"""
# Sort the ratings to find the highest and lowest... | from solution import calculate_car, process_products
def test_calculate_car_with_various_ratings():
assert calculate_car([1, 2, 3, 4, 5]) == 3.00
assert calculate_car([2, 3, 3, 3, 4, 5]) == 3.25
def test_calculate_car_with_same_ratings():
assert calculate_car([4, 4, 4, 4, 4]) == 4.00
def test_calculate_c... | [
{
"docstring": "Calculate the Critical Average Rating (CAR) for a list of ratings.\n\nArgs:\nratings (list): List of integers representing the ratings.\n\nReturns:\nfloat: The CAR value rounded to two decimal places.",
"function_declaration": "def calculate_car(ratings):",
"function_name": "calculate_ca... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005484_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def calculate_car(ratings):\n \"\"\"\n Calculate the Critical Average Rating (CAR) for a list of ratings.\n \n Args:\n ratings (list): List of ... | trial_gpt4o_0 | {
"original_instruction": "A new online shopping website uses a rating system for product reviews. Customers rate products on a scale of 1 to 5 stars. To make the ratings fairer, the website wants to implement a feature called \"Critical Average Rating\" (CAR). The CAR of a product is defined as the average rating af... | 0.647823 | Codeforces_21058 | C | [
"calculate_car",
"process_products"
] | 2 | [
[
"process_products",
"calculate_car"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 74ec8fa96d43c2e06faceaa0402993b505295e5e | 15a4a9bee7725545c0fa3af483f28462a9d74f42 | |||
v1.0 | complete | Codeforces | Codeforces_21666_C | from typing import List, Tuple
from sympy import isprime
def prime_subset(n: int) -> str:
""" Determines if there exists a subset of the first N natural numbers such
that the sum of the subset is a prime number.
>>> prime_subset(5)
'YES\n1 2 3 4 5'
>>> prime_subset(10)
'YES\n2 3 5'
>>> prim... | from sympy import isprime
def find_prime_subset(n):
# Use the sum of the first n natural numbers formula
total_sum = n * (n + 1) // 2
# Check if the sum is prime
if isprime(total_sum):
return ("YES", list(range(1, n + 1)))
# Try to find subsets by excluding one number
for i in... | from solution import prime_subset
def test_prime_subset_case_1():
result = prime_subset(5)
assert result.startswith("YES")
def test_prime_subset_case_2():
result = prime_subset(10)
assert result.startswith("YES")
def test_prime_subset_small_number():
result = prime_subset(1)
assert result == ... | [
{
"docstring": null,
"function_declaration": "def find_prime_subset(n):",
"function_name": "find_prime_subset",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def prime_subset(n):",
"function_name": "prime_subset",
"parameter_list": "(n)"
}
] | [
0,
0,
0,
0,
0,
0,
0,
0,
1,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005484_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef is_prime(num):\n if num <= 1:\n return False\n if num <= 3:\n return True\n if num % 2 == 0 or num % 3 == 0:\n ... | trial_gpt4o_8 | {
"original_instruction": "Yak has recently developed a keen interest in prime numbers. He is fascinated by the uniqueness of prime numbers and the fact that they have only two distinct positive divisors: 1 and themselves. One day, Yak came across an interesting problem and needs your help to solve it.\n\nGiven an in... | 0.762178 | Codeforces_21666 | C | [
"find_prime_subset",
"prime_subset"
] | 2 | [
[
"prime_subset",
"find_prime_subset"
]
] | 1 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | b72b6d69ee30e22e4e4c1460bb514df765081195 | 5758141ba23e2c29c15d57c870ce27a1576cbbb7 | |||
v1.0 | complete | Codeforces | Codeforces_21610_C | def count_inversions(arr):
"""
Function to count the number of inversions in the array.
"""
# Unit Tests
def test_no_inversions():
assert count_inversions([1, 2, 3, 4, 5]) == 0
def test_all_reversed():
assert count_inversions([5, 4, 3, 2, 1]) == 10
def test_some_inversions():
assert count_in... | def count_inversions(arr):
"""
Function to count the number of inversions in the array.
"""
if not arr:
return 0
n = len(arr)
temp_arr = [0]*n
return _merge_sort(arr, temp_arr, 0, n-1)
def _merge_sort(arr, temp_arr, left, right):
"""
Utility function to perform mergesor... | from solution import count_inversions
def test_no_inversions():
assert count_inversions([1, 2, 3, 4, 5]) == 0
def test_all_reversed():
assert count_inversions([5, 4, 3, 2, 1]) == 10
def test_some_inversions():
assert count_inversions([2, 3, 8, 6, 1]) == 5
def test_single_element():
assert count_inve... | [
{
"docstring": "Function to count the number of inversions in the array.",
"function_declaration": "def count_inversions(arr):",
"function_name": "count_inversions",
"parameter_list": "(arr)"
},
{
"docstring": "Utility function to perform mergesort and count inversions.",
"function_decla... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005484_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def count_inversions(arr):\n \"\"\"\n Counts the number of inversions in the array.\n \n Parameters:\n arr (list of int): The input array o... | trial_gpt4o_2 | {
"original_instruction": "Given an array of integers, an inversion is defined as a pair of indices (i, j) such that i < j and a[i] > a[j]. Your task is to count the number of inversions in the array.\n\nThe first line contains a single integer n (1 ≤ n ≤ 10^5), representing the number of elements in the array.\nThe ... | 0.775673 | Codeforces_21610 | C | [
"count_inversions",
"_merge_sort",
"_merge"
] | 3 | [
[
"_merge_sort",
"_merge"
],
[
"count_inversions",
"_merge_sort"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | cae73532e923e110f0ebe2852ce401329e8554d8 | c1201de369050a1c3bb9c0272f967d26e1d87a74 | |||
v1.0 | complete | Codeforces | Codeforces_21216_C | def can_return_to_initial(n, initial_collection, trade_offers):
""" Determine if Mary can return to her initial stamp collection after a series of trades.
Args:
n: Integer, number of stamps in the initial collection.
initial_collection: List of integers representing the initial stamp collection.
... | def can_return_to_initial(n, initial_collection, trade_offers):
from collections import deque
initial_collection_set = set(initial_collection)
# If there is a trade that exactly swaps initial_collection elements
for out_trade, in_trade in trade_offers:
if set(out_trade) == initial_coll... | from solution import solve
def test_case_1():
trades_info = [
(5, [1, 2, 3, 4, 5], [
([1, 2, 3, 4, 5], [6, 7, 8, 9, 10]),
([6, 7, 8, 9, 10], [1, 2, 3, 4, 5])
]),
(5, [1, 2, 3, 4, 5], [
([1, 2, 3, 4, 5], [6, 7, 8, 9, 10]),
([6, 7, 8, 9, 10], [1... | [
{
"docstring": null,
"function_declaration": "def can_return_to_initial(n, initial_collection, trade_offers):",
"function_name": "can_return_to_initial",
"parameter_list": "(n, initial_collection, trade_offers)"
},
{
"docstring": null,
"function_declaration": "def solve(trades_info):",
... | [
0,
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005484_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def can_return_to_initial_collection(t, test_cases):\n results = []\n for test_case in test_cases:\n n, initial_collection, m, trades = test_case... | trial_gpt4o_7 | {
"original_instruction": "Mary loves collecting rare stamps. She has a collection of `n` stamps, each uniquely identified by an integer from 1 to `n`. Stamps can be traded through a special stamp trading platform which allows Mary to offer her collection as a package and receive a completely different package of the... | 0.602178 | Codeforces_21216 | C | [
"can_return_to_initial",
"solve"
] | 2 | [
[
"solve",
"can_return_to_initial"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6f05a325f219e08ba3bd24c861bf1021f0f10bec | 44f46bbc55584d0e356a545f3dc30e44ebc61ceb | |||
v1.0 | complete | Codeforces | Codeforces_21838_C | def largest_special_subset_size(strings: List[str]) -> int:
""" Returns the size of the largest special subset from the given strings.
A subset of strings is considered special if, for any two different strings
in the subset, one string is not a substring of the other.
>>> largest_special_subset_size(["... | def is_special_subset(subset):
"""
Check if a given subset is special.
"""
for i in range(len(subset)):
for j in range(len(subset)):
if i != j and (subset[i] in subset[j] or subset[j] in subset[i]):
return False
return True
def largest_special_subset_size(strings... | from solution import largest_special_subset_size
def test_example_case():
assert largest_special_subset_size(["abc", "ab", "bca", "d"]) == 3
def test_single_string():
assert largest_special_subset_size(["a"]) == 1
def test_no_special_subset():
assert largest_special_subset_size(["a", "aa", "aaa"]) == 1
... | [
{
"docstring": "Check if a given subset is special.",
"function_declaration": "def is_special_subset(subset):",
"function_name": "is_special_subset",
"parameter_list": "(subset)"
},
{
"docstring": "Returns the size of the largest special subset from the given strings.",
"function_declara... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005484_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_special_subset(subset):\n \"\"\"\n Check if a given subset is special.\n \"\"\"\n for i in range(len(subset)):\n for j in range(len(... | trial_gpt4o_0 | {
"original_instruction": "Alice has a collection of strings and wants to find a special kind of subset from this collection. A subset of strings S is considered special if, for any two different strings in the subset, one string is not a substring of the other. \n\nYou are given n strings. Your task is to find the s... | 0.612305 | Codeforces_21838 | C | [
"is_special_subset",
"largest_special_subset_size"
] | 2 | [
[
"largest_special_subset_size",
"is_special_subset"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 90d37b428869ac412d719c6204a6401904d89c33 | 0bc11a73abcdbe9707fb4d85038b8c24ced0c007 | |||
v1.0 | complete | Codeforces | Codeforces_21822_C | from typing import List
def min_steps_to_treasure(n: int, m: int, k: int, grid: List[str]) -> int:
""" Find the minimum number of steps required to get to the treasure
if it's possible, or return -1 if it's not possible.
>>> min_steps_to_treasure(4, 4, 1, ["....", "...#", "..T.", "#..."])
4
>... | from collections import deque
def is_within_bounds(x, y, n, m):
return 0 <= x < n and 0 <= y < m
def bfs_to_treasure(grid, n, m):
directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
start = (0, 0)
if grid[0][0] == '#' or grid[0][0] == 'T': # Start is blocked or start is the treasure
return -... | from solution import min_steps_to_treasure
def test_example():
n, m, k = 4, 4, 1
grid = [
"....",
"...#",
"..T.",
"#..."
]
assert min_steps_to_treasure(n, m, k, grid) == 4
def test_unreachable_treasure():
n, m, k = 4, 4, 1
grid = [
"....",
"####"... | [
{
"docstring": null,
"function_declaration": "def is_within_bounds(x, y, n, m):",
"function_name": "is_within_bounds",
"parameter_list": "(x, y, n, m)"
},
{
"docstring": null,
"function_declaration": "def bfs_to_treasure(grid, n, m):",
"function_name": "bfs_to_treasure",
"paramet... | [
0,
0,
0,
0,
1
] | 1 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005484_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import deque\n\ndef min_steps_to_treasure(n, m, k, grid):\n def in_bounds(x, y):\n return 0 <= x < n and 0 <= y < m\n \n dire... | trial_gpt4o_4 | {
"original_instruction": "To celebrate her birthday, Alice has planned a treasure hunt for her friends. She has hidden the treasure in one of the rooms in her house. The house can be represented as a grid of size \\( n \\times m \\), with each cell representing a different room. Each room can have one of the three p... | 0.596942 | Codeforces_21822 | C | [
"is_within_bounds",
"bfs_to_treasure",
"min_steps_to_treasure"
] | 3 | [
[
"bfs_to_treasure",
"is_within_bounds"
],
[
"min_steps_to_treasure",
"bfs_to_treasure"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 41374633a4209687e8244d3785bc33cf96947974 | fd3c2083ad844923f289ca74cdc11e10c2f67bb1 | |||
v1.0 | complete | Codeforces | Codeforces_21456_C | from typing import List
def subset_sum_exists(n: int, k: int, arr: List[int]) -> str:
"""
Returns "YES" if there exists a subset of the array arr with length n
that sums to k, otherwise returns "NO"
>>> subset_sum_exists(6, 9, [3, 34, 4, 12, 5, 2])
'YES'
>>> subset_sum_exists(3, 7, [1, 2, 3])
... | from itertools import combinations
def subset_sum_exists(n, k, arr):
"""
Returns "YES" if there exists a subset of the array arr with length n
that sums to k, otherwise returns "NO"
"""
for i in range(n + 1):
for subset in combinations(arr, i):
if sum(subset) == k:
... | from solution import subset_sum_exists
def test_subset_sum_exists():
assert subset_sum_exists(6, 9, [3, 34, 4, 12, 5, 2]) == "YES"
assert subset_sum_exists(3, 7, [1, 2, 3]) == "NO"
assert subset_sum_exists(4, 0, [1, 2, 3, 4]) == "YES"
assert subset_sum_exists(5, 5, [1, 2, 5, 3, 7]) == "YES"
assert ... | [
{
"docstring": "Returns \"YES\" if there exists a subset of the array arr with length n\nthat sums to k, otherwise returns \"NO\"",
"function_declaration": "def subset_sum_exists(n, k, arr):",
"function_name": "subset_sum_exists",
"parameter_list": "(n, k, arr)"
},
{
"docstring": null,
"... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005484_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def subset_sum_exists(n, k, array):\n \"\"\"\n Returns \"YES\" if there exists a subset of array that sums to k, otherwise \"NO\".\n \"\"\"\n # Us... | trial_gpt4o_2 | {
"original_instruction": "You are given a list of integers. You have to determine if there exists a subset of these integers which sums to a given value.\n\nMore formally, you are given an integer array $$$a$$$ of length $$$n$$$ and an integer $$$k$$$. Determine if there exists a subset of the array $$$a$$$ such tha... | 0.608548 | Codeforces_21456 | C | [
"subset_sum_exists",
"process_test_cases",
"solve"
] | 3 | [
[
"process_test_cases",
"subset_sum_exists"
],
[
"solve",
"process_test_cases"
]
] | 2 | [
"process_test_cases"
] | false | [] | false | pytest | true | [] | true | 5d45ca8613a9851f0cde8b6733dee413309aa779 | b6fb49f435748331c5a9c6af427ec921f60ffdc1 | |||
v1.0 | complete | Codeforces | Codeforces_21631_C | from typing import List, Tuple
def minimum_energy(n: int, m: int, edges_data: List[Tuple[int, int, int]]) -> int:
""" Determine the minimum amount of magical energy required to connect all nodes in the forest using Kruskal's MST algorithm.
>>> minimum_energy(4, 5, [(1, 2, 1), (1, 3, 2), (1, 4, 3), (2, 3, ... | def find(parent, i):
if parent[i] == i:
return i
else:
return find(parent, parent[i])
def union(parent, rank, x, y):
root_x = find(parent, x)
root_y = find(parent, y)
if rank[root_x] < rank[root_y]:
parent[root_x] = root_y
elif rank[root_x] > rank[root_y]:
paren... | def test_minimum_energy():
assert minimum_energy(4, 5, [(1, 2, 1), (1, 3, 2), (1, 4, 3), (2, 3, 4), (3, 4, 5)]) == 6
def test_minimum_energy_single_edge():
assert minimum_energy(2, 1, [(1, 2, 10)]) == 10
def test_minimum_energy_all_equal_weights():
assert minimum_energy(3, 3, [(1, 2, 5), (2, 3, 5), (1... | [
{
"docstring": null,
"function_declaration": "def find(parent, i):",
"function_name": "find",
"parameter_list": "(parent, i)"
},
{
"docstring": null,
"function_declaration": "def union(parent, rank, x, y):",
"function_name": "union",
"parameter_list": "(parent, rank, x, y)"
},
... | [
0,
0,
0,
0,
0,
0,
1,
1,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005484_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def find(parent, i):\n if parent[i] == i:\n return i\n return find(parent, parent[i])\n\ndef union(parent, rank, x, y):\n root_x = find(parent... | trial_gpt4o_6 | {
"original_instruction": "There is a magical forest that can be represented as an undirected, weighted graph with `n` nodes and `m` edges. Each node represents a magical tree and each edge represents a path that connects two magical trees with a magical energy cost.\n\nThe forest guardian wants to ensure that each p... | 0.596776 | Codeforces_21631 | C | [
"find",
"union",
"kruskal",
"minimum_energy"
] | 4 | [
[
"kruskal",
"find"
],
[
"kruskal",
"union"
],
[
"minimum_energy",
"kruskal"
],
[
"union",
"find"
]
] | 4 | [] | false | [] | false | pytest | false | [] | true | 36860438ca714bfb042d6727e23a44684290df85 | e659cd4e0cd144869ed4e18fd293ed4e99961d93 | |||
v1.0 | complete | Codeforces | Codeforces_21063_C | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def build_tree(n: int, links: List[Tuple[int, int, int]]) -> TreeNode:
""" Build a binary tree from the given number of nodes and list of links.
Args:
n (int): The number of nodes in the tree.... | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def build_tree(n, links):
nodes = {i: TreeNode(i) for i in range(1, n+1)}
for parent, child, is_left in links:
if is_left:
nodes[parent].left = nodes[child]
else:
... | from solution import TreeNode, build_tree, find_LCA, get_lca
def test_example_case():
n = 6
links = [(1, 2, 1), (1, 3, 0), (2, 4, 1), (2, 5, 0), (3, 6, 0)]
p, q = 4, 6
assert get_lca(n, links, p, q) == 1
def test_lca_2_and_3():
n = 6
links = [(1, 2, 1), (1, 3, 0), (2, 4, 1), (2, 5, 0), (3, 6, ... | [] | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005484_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\ndef build_tree(edges):\n nodes = ... | trial_gpt4o_1 | {
"original_instruction": "In a binary tree, each node contains a value, and each node has zero, one, or two children. You need to write a function that finds the lowest common ancestor (LCA) of two given nodes in the tree. The lowest common ancestor is defined between two nodes `p` and `q` as the lowest node in the ... | 0.592399 | Codeforces_21063 | C | [
"build_tree",
"find_LCA",
"get_lca"
] | 3 | [
[
"get_lca",
"build_tree"
],
[
"get_lca",
"find_LCA"
]
] | 2 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | cc1c80bcdcca8fc13e400e7303195586f3ee4bd4 | 18dd9f4172d942bd82c770c3ba4b65bbe49a6403 | |||
v1.0 | complete | Codeforces | Codeforces_21586_C | from typing import List
def largest_rectangle_area(n: int, m: int, grid: List[List[int]]) -> int:
"""
Given an integer matrix of size N x M where each entry can be either 0 or 1,
determine the area of the largest rectangle containing only 1s.
Parameters:
n (int): Number of rows in the matrix
... | def largest_rectangle_of_1s(matrix):
"""
Given a matrix with 0s and 1s, finds the largest rectangle containing only 1s.
"""
if not matrix or not matrix[0]:
return 0
n = len(matrix)
m = len(matrix[0])
max_area = 0
heights = [0] * m
def largest_histogram_area(heights):
... | from solution import largest_rectangle_area
def test_example_case():
matrix = [
[1, 0, 1, 0, 0],
[1, 0, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 0, 0, 1, 0],
]
assert largest_rectangle_area(4, 5, matrix) == 6
def test_single_row():
matrix = [
[1, 1, 1, 1, 1],
]
as... | [
{
"docstring": "Given a matrix with 0s and 1s, finds the largest rectangle containing only 1s.",
"function_declaration": "def largest_rectangle_of_1s(matrix):",
"function_name": "largest_rectangle_of_1s",
"parameter_list": "(matrix)"
},
{
"docstring": null,
"function_declaration": "def l... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005484_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def maximalRectangle(matrix):\n if not matrix:\n return 0\n \n n = len(matrix)\n m = len(matrix[0])\n max_area = 0\n heights = [0] * ... | trial_gpt4o_2 | {
"original_instruction": "You are given an integer matrix of size $$$N \\times M$$$ where each entry can be either 0 or 1. A rectangle within this matrix is defined by four integers $$$r1, c1, r2, c2$$$ (1 ≤ r1 ≤ r2 ≤ N and 1 ≤ c1 ≤ c2 ≤ M), which represent the top-left and bottom-right coordinates of the rectangle,... | 0.763466 | Codeforces_21586 | C | [
"largest_rectangle_of_1s",
"largest_rectangle_area"
] | 2 | [
[
"largest_rectangle_area",
"largest_rectangle_of_1s"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | db0826500f1354862719e116e40bcd53bdea876b | d6e97d2f9d6333ede9aca99b624286ec66efe328 | |||
v1.0 | complete | Codeforces | Codeforces_21891_C | from typing import List
def min_tsp_route_length(n: int, distance_matrix: List[List[int]]) -> int:
""" Determine the length of the shortest possible route that visits
every habitat exactly once and returns to the starting point.
>>> min_tsp_route_length(4, [
[0, 10, 15, 20],
[10, 0, 35, 25],
... | from itertools import permutations
def calculate_tsp(n, distances):
# generate all permutations of habitats to be visited (excluding the return to start point)
habitats = range(n)
min_route_length = float('inf')
# iterate through all possible tours
for perm in permutations(habitats):
c... | from solution import min_tsp_route_length
def test_case_1():
n = 4
distance_matrix = [
[0, 10, 15, 20],
[10, 0, 35, 25],
[15, 35, 0, 30],
[20, 25, 30, 0]
]
assert min_tsp_route_length(n, distance_matrix) == 80
def test_case_2():
n = 3
distance_matrix = [
... | [
{
"docstring": null,
"function_declaration": "def calculate_tsp(n, distances):",
"function_name": "calculate_tsp",
"parameter_list": "(n, distances)"
},
{
"docstring": null,
"function_declaration": "def min_tsp_route_length(n, distance_matrix):",
"function_name": "min_tsp_route_lengt... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005484_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from itertools import permutations\n\ndef calculate_tsp(n, distances):\n # generate all permutations of habitats to be visited (excluding the return to sta... | trial_gpt4o_0 | {
"original_instruction": "Calixta is planning her next photo expedition to capture some rare species of birds. She plans to visit each bird habitat only once to minimize the disturbance to the birds. Each habitat is connected by footpaths, and she wants to make sure that she takes the shortest possible route that vi... | 0.623603 | Codeforces_21891 | C | [
"calculate_tsp",
"min_tsp_route_length"
] | 2 | [
[
"min_tsp_route_length",
"calculate_tsp"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 477b5c7074277d187e2cdc815e318100b1f54776 | a5d988f57e4ea81e5215320aea13c3fccb8f5262 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.