/************************************************ Grundlegende Algorithmen mit Java, http://algorithmen-und-problemloesungen.de/ Copyright @2007-2008 by Doina Logofatu in C#: Michael Gärtner ************************************************/ using System; using System.Collections.Generic; using System.IO; namespace Logofatu { class P01Rucksack { private static String FileInputName = "rucksack.in"; private static String FileOutputName = "rucksack.out"; // Ein- und Ausgabe von Zahlen im englischen Format ('.' statt ',' als Dezimaltrennzeichen) private static IFormatProvider formatProvider = System.Globalization.CultureInfo.GetCultureInfo("en-US").NumberFormat; class RucksackObject : IComparable { private int index; private float weight, value; public RucksackObject(int index, float weight, float value) { this.index = index; this.weight = weight; this.value = value; } public int CompareTo(RucksackObject other) { float diff = this.value / this.weight - other.value / other.weight; return diff > 0f ? 1 : (diff < 0f ? -1 : 0); } public override String ToString() { return "Objekt " + this.index + ": " + this.weight.ToString(formatProvider) + " " + this.value.ToString(formatProvider); } public float Weight { get { return weight; } } } static void Main(string[] args) { // Daten einlesen StreamReader sr = new StreamReader(FileInputName); StreamWriter sw = new StreamWriter(FileOutputName); float M = float.Parse(sr.ReadLine(), formatProvider); List v = new List(); int index = 0; while ( !sr.EndOfStream ) { string[] sArray = sr.ReadLine().Split(' '); float weight = float.Parse(sArray[0], formatProvider); float value = float.Parse(sArray[1], formatProvider); v.Add(new RucksackObject(++index, weight, value)); } sr.Close(); // Rucsackobjekte sortieren mit CompareTo-Methode v.Sort(); // Algorithmus int i = v.Count - 1; while ( i > 0 && M > 0 ) { float wgt = v[i].Weight; if ( M >= wgt ) { M -= wgt; --i; } else { M = -M; } } // Ausgabe for ( int j = v.Count - 1; j > i; --j ) { sw.Write(v[j]); sw.WriteLine(" - vollstaendig"); } if ( i >= 0 && M < 0 ) { sw.Write(v[i]); sw.Write(" - "); sw.Write((-M).ToString("F2", formatProvider)); sw.Write(" kg"); } sw.Close(); } } }