Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions DataStructures/Trees/Heap/Deadline
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import sys
from typing import List, Tuple

def main() -> None:
input_data = sys.stdin.read().strip().splitlines()
n: int = int(input_data[0])
problems: List[Tuple[int, int]] = []

for line in input_data[1:]:
parts = line.split()
if len(parts) == 2:
problems.append((int(parts[0]), int(parts[1])))
else:
raise ValueError("Each line must contain exactly two integers")

print(solve(n, problems))

if __name__ == "__main__":
main()
73 changes: 73 additions & 0 deletions DataStructures/Trees/Heap/Deadline Scheduling/atcoder/A75/A75.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
package main

import (
"bufio"
"container/heap"
"fmt"
"os"
"sort"
"strconv"
"strings"
)

// 問題の構造体
type Problem struct {
T int // 所要時間
D int // 締切
}

// 最大ヒープの実装
type MaxHeap []int

func (h MaxHeap) Len() int { return len(h) }
func (h MaxHeap) Less(i, j int) bool { return h[i] > h[j] } // 逆順で最大ヒープに
func (h MaxHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *MaxHeap) Push(x interface{}) { *h = append(*h, x.(int)) }
func (h *MaxHeap) Pop() interface{} {
old := *h
n := len(old)
x := old[n-1]
*h = old[0 : n-1]
return x
}

func solve(N int, problems []Problem) int {
// 締切 D で昇順ソート
sort.Slice(problems, func(i, j int) bool {
return problems[i].D < problems[j].D
})

totalTime := 0
h := &MaxHeap{}
heap.Init(h)

for _, p := range problems {
totalTime += p.T
heap.Push(h, p.T)

if totalTime > p.D {
removed := heap.Pop(h).(int)
totalTime -= removed
}
}

return h.Len()
}

func main() {
scanner := bufio.NewScanner(os.Stdin)
scanner.Scan()
N, _ := strconv.Atoi(scanner.Text())

var problems []Problem
for i := 0; i < N; i++ {
scanner.Scan()
parts := strings.Fields(scanner.Text())
T, _ := strconv.Atoi(parts[0])
D, _ := strconv.Atoi(parts[1])
problems = append(problems, Problem{T, D})
}

result := solve(N, problems)
fmt.Println(result)
}
64 changes: 64 additions & 0 deletions DataStructures/Trees/Heap/Deadline Scheduling/atcoder/A75/A75.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
<?php

declare(strict_types=1);

/**
* 問題データの型:int T(所要時間), int D(締切)
*/
class Problem {
public int $T;
public int $D;

public function __construct(int $T, int $D) {
$this->T = $T;
$this->D = $D;
}
}

/**
* メインの問題解決ロジック
*
* @param int $N
* @param array<Problem> $problems
* @return int
*/
function solve(int $N, array $problems): int {
// 締切Dの昇順でソート
usort($problems, function (Problem $a, Problem $b): int {
return $a->D <=> $b->D;
});

/** @var SplPriorityQueue<int> $heap 最大ヒープとして使用 */
$heap = new SplPriorityQueue();
$totalTime = 0;

foreach ($problems as $p) {
$totalTime += $p->T;
$heap->insert($p->T, $p->T); // priority = T なので最大ヒープ動作

if ($totalTime > $p->D) {
$removed = $heap->extract();
$totalTime -= $removed;
}
}

return $heap->count();
}

/**
* 標準入力からの処理
*/
function main(): void {
$lines = explode("\n", trim(file_get_contents("php://stdin")));
$N = intval(array_shift($lines));
$problems = [];

foreach ($lines as $line) {
[$T, $D] = array_map('intval', explode(" ", $line));
$problems[] = new Problem($T, $D);
}

echo solve($N, $problems) . PHP_EOL;
}

main();
37 changes: 37 additions & 0 deletions DataStructures/Trees/Heap/Deadline Scheduling/atcoder/A75/A75.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import sys
import heapq
from typing import List, Tuple

def solve(n: int, problems: List[Tuple[int, int]]) -> int:
# 締切Dで昇順ソート
problems.sort(key=lambda x: x[1])

total_time: int = 0
max_heap: List[int] = [] # Pythonはmin-heapなので、-Tを使って最大ヒープにする

for t, d in problems:
total_time += t
heapq.heappush(max_heap, -t) # 最大ヒープとして扱うため -t

if total_time > d:
removed: int = -heapq.heappop(max_heap) # 最大値(時間のかかる問題)を除く
total_time -= removed

return len(max_heap)

def main() -> None:
input_data = sys.stdin.read().strip().splitlines()
n: int = int(input_data[0])
problems: List[Tuple[int, int]] = []

for line in input_data[1:]:
parts = line.split()
if len(parts) == 2:
problems.append((int(parts[0]), int(parts[1])))
else:
raise ValueError("Each line must contain exactly two integers")

print(solve(n, problems))

if __name__ == "__main__":
main()
88 changes: 88 additions & 0 deletions DataStructures/Trees/Heap/Deadline Scheduling/atcoder/A75/A75.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import * as fs from 'fs';

// 最大ヒープ(Max Heap)クラスの定義
class MaxHeap {
private data: number[] = [];

push(val: number): void {
this.data.push(val);
this.bubbleUp(this.data.length - 1);
}

pop(): number | null {
if (this.data.length === 0) return null;
const max = this.data[0];
const last = this.data.pop()!;
if (this.data.length > 0) {
this.data[0] = last;
this.bubbleDown(0);
}
return max;
}

size(): number {
return this.data.length;
}

private bubbleUp(index: number): void {
while (index > 0) {
const parent = Math.floor((index - 1) / 2);
if (this.data[parent] >= this.data[index]) break;
[this.data[parent], this.data[index]] = [this.data[index], this.data[parent]];
index = parent;
}
}

private bubbleDown(index: number): void {
const length = this.data.length;
while (true) {
let left = 2 * index + 1;
let right = 2 * index + 2;
let largest = index;

if (left < length && this.data[left] > this.data[largest]) {
largest = left;
}
if (right < length && this.data[right] > this.data[largest]) {
largest = right;
}
if (largest === index) break;

[this.data[largest], this.data[index]] = [this.data[index], this.data[largest]];
index = largest;
}
}
}

// メイン処理関数
function main(input: string): void {
const lines = input.trim().split('\n');
const N = parseInt(lines[0]);
const problems: { T: number; D: number }[] = [];

for (let i = 1; i <= N; i++) {
const [T, D] = lines[i].split(' ').map(Number);
problems.push({ T, D });
}

// 締切D順にソート
problems.sort((a, b) => a.D - b.D);

const heap = new MaxHeap();
let totalTime = 0;

for (const { T, D } of problems) {
totalTime += T;
heap.push(T);

if (totalTime > D) {
const removed = heap.pop()!;
totalTime -= removed;
}
}

console.log(heap.size());
}

// 標準入力の読み込み
main(fs.readFileSync(0, 'utf8'));
35 changes: 35 additions & 0 deletions DataStructures/Trees/Heap/Deadline Scheduling/atcoder/A75/A75_1.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
const fs = require("fs");

function main(input) {
const lines = input.trim().split("\n");
const N = parseInt(lines[0]);
const problems = lines.slice(1).map(line => {
const [T, D] = line.split(" ").map(Number);
return { T, D };
});

// 締切順にソート
problems.sort((a, b) => a.D - b.D);

// 優先度付きキュー(最大ヒープ)として時間を格納する
const timeHeap = [];
let currentTime = 0;

for (const { T, D } of problems) {
currentTime += T;
timeHeap.push(T);
// 最大ヒープを保つため降順にソート
timeHeap.sort((a, b) => b - a);

// 締切を超えたら、最も時間のかかる問題を削除
if (currentTime > D) {
const longest = timeHeap.shift(); // 最大値を削除
currentTime -= longest;
}
}

console.log(timeHeap.length);
}

// 標準入力から
main(fs.readFileSync(0, "utf8"));
Loading