Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Resolução do problema 01 #25

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
6 changes: 6 additions & 0 deletions submissions/erickcestari/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
[package]
name = "erickcestari"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
13 changes: 13 additions & 0 deletions submissions/erickcestari/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# How to run

Need to have installed rust and run the following commands:

``` bash
cargo run --release -- your_filename.txt
```

## example

``` bash
cargo run --release -- ../../resources/instances/problem_01/exemplo_02.txt
```
63 changes: 63 additions & 0 deletions submissions/erickcestari/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
use std::{
cmp, env,
fs::File,
io::{self, BufRead},
};

fn knapsack(seeds: &Vec<(usize, usize)>, capacity: usize) -> usize {
let n = seeds.len();
let mut dp = vec![vec![0; (capacity + 1) as usize]; n + 1];

for i in 1..=n {
for j in 0..=capacity {
if seeds[i - 1].0 > j {
dp[i][j] = dp[i - 1][j];
} else {
dp[i][j] = cmp::max(
dp[i - 1][j],
dp[i - 1][(j - seeds[i - 1].0) as usize] + seeds[i - 1].1,
);
}
}
}

dp[n][capacity]
}

fn main(){
let args: Vec<String> = env::args().collect();
if args.len() < 2 {
eprintln!("Usage: {} <filename>", args[0]);
std::process::exit(1);
}
let filename = &args[1];

let path = std::path::Path::new(filename);
let file = File::open(&path).unwrap();

let lines: Vec<_> = io::BufReader::new(file)
.lines()
.map(|line| line.unwrap())
.collect();

let first_line: Vec<usize> = lines[0]
.split_whitespace()
.map(|s| s.parse().unwrap())
.collect();

let capacity = first_line[1];

let seeds: Vec<(usize, usize)> = lines[1..]
.iter()
.map(|line| {
let mut iter = line.split_whitespace();
let space: usize = iter.next().unwrap().parse().unwrap();
let value: usize = iter.next().unwrap().parse().unwrap();
(space, value)
})
.collect();

let result = knapsack(&seeds, capacity);

println!("Maior lucro possível: {}", result);
}