Last active
October 23, 2016 01:25
-
-
Save ruslander/1cfa49ee3ac8fd51a595f24f40905560 to your computer and use it in GitHub Desktop.
Second week algorhitms
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class FractionalKnapsack { | |
public static class Loot implements Comparable{ | |
public Loot(int i, int v, int w){ | |
Index = i; | |
Ratio = (double)v / w; | |
Weight = w; | |
Benefit = v; | |
} | |
public int Weight; | |
public int Benefit; | |
public int Index; | |
public double Ratio; | |
@Override | |
public int compareTo(Object o) { | |
return Double.compare(((Loot)o).Ratio, this.Ratio); | |
} | |
} | |
private static double getOptimalValue(int capacity, int[] values, int[] weights) { | |
ArrayList<Loot> items = new ArrayList<>(); | |
for (int i = 0; i < values.length; i++) { | |
items.add(new Loot(i, values[i], weights[i])); | |
} | |
Collections.sort(items); | |
int W = 0; | |
double value = 0; | |
for (int i = 0; i < items.size(); i++) { | |
if(W == capacity) | |
break; | |
Loot item = items.get(i); | |
if(W + item.Weight <= capacity){ | |
W = W + item.Weight; | |
value = value + item.Benefit; | |
}else { | |
int roomLeft = capacity - W; | |
value = value + (roomLeft * item.Ratio); | |
W = W + roomLeft; | |
} | |
//System.out.println(i + ") Value " + value + " Room " + W + "/" + capacity); | |
} | |
return Math.round(value*10000)/10000.0d; | |
} | |
public static void main(String args[]) { | |
Scanner scanner = new Scanner(System.in); | |
int n = scanner.nextInt(); | |
int capacity = scanner.nextInt(); | |
int[] values = new int[n]; | |
int[] weights = new int[n]; | |
for (int i = 0; i < n; i++) { | |
values[i] = scanner.nextInt(); | |
weights[i] = scanner.nextInt(); | |
} | |
System.out.println(getOptimalValue(capacity, values, weights)); | |
} | |
} | |
public class Change { | |
private static int getChange(int m) { | |
int[] types = new int[]{10,5,1}; | |
int totalCoins = 0; | |
for (int i = 0; i < types.length; i++) { | |
int coins = m / types[i]; | |
int reminder = m % types[i]; | |
if(coins != 0){ | |
totalCoins = totalCoins + coins; | |
m = reminder; | |
} | |
if(coins == 0) | |
continue; | |
if(reminder == 0){ | |
break; | |
} | |
} | |
return totalCoins; | |
} | |
public static void main(String[] args) { | |
Scanner scanner = new Scanner(System.in); | |
int m = scanner.nextInt(); | |
System.out.println(getChange(m)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment