Loading...

Във форума е въведено ограничение, което позволява на потребителите единствено да разглеждат публикуваните въпроси.

adelina_t avatar adelina_t 2 Точки

Kamino Factory - 60/100

Здравейте,

Това може би е доста безумен начин за решаване на тази задача,но на този етап друго не можах да измисля.

Това е условието на задачата:

1.*Kamino Factory

The clone factory in Kamino got another order to clone troops. But this time you are tasked to find the best DNA sequence to use in the production.

You will receive the DNA length and until you receive the command "Clone them!" you will be receiving a DNA sequences of ones and zeroes, split by "!" (one or several).

You should select the sequence with the longest subsequence of ones. If there are several sequences with same length of subsequence of ones, print the one with the leftmost starting index, if there are several sequences with same length and starting index, select the sequence with the greater sum of its elements.

After you receive the last command "Clone them!" you should print the collected information in the following format:

"Best DNA sample {bestSequenceIndex} with sum: {bestSequenceSum}."

"{DNA sequence, joined by space}"

Input / Constraints

  • The first line holds the length of the sequencesinteger in range [1…100];
  • On the next lines until you receive "Clone them!" you will be receiving sequences (at least one) of ones and zeroes, split by "!" (one or several).

 Output

The output should be printed on the console and consists of two lines in the following format:

"Best DNA sample {bestSequenceIndex} with sum: {bestSequenceSum}."

"{DNA sequence, joined by space}"

 Examples

Input

Output

Comments

5

1!0!1!1!0

0!1!1!0!0

Clone them!

Best DNA sample 2 with sum: 2.

0 1 1 0 0

We receive 2 sequences with same length of subsequence of ones, but the second is printed, because its subsequence starts at index[1].

Input

Output

Comments

4

1!1!0!1

1!0!0!1

1!1!0!0

Clone them!

Best DNA sample 1 with sum: 3.

1 1 0 1

We receive 3 sequences. Both 1 and 3 have same length of subsequence of ones -> 2, and both start from index[0], but the first is printed, because its sum is greater.

Това,което успях да измисля като решение е да пазя 3 листа с информация - един за поредността на единиците,един за индексите и един за сумата.След това започвам да ги чистя по дадените условия и накрая принтирам резултата.Judge ми дава 60/100.Пробвах доста варианти за вход,но на всичко,което пробвам работи - явно не мога да се сетя при какъв вход би гръмнало.

Искам да помоля за преработка на текущия код за решаване на задачата и също така за варианти за скъсяване на кода/особено в края,където пазя в стринг резултата,защото,когато се опитвам да принтирам по друг начин ми излиза System32 на конзолата).

Това ми е кода:

using System;
using System.Linq;
using System.Collections.Generic;

namespace Kamino_Factory
{
    class Program
    {
        static void Main(string[] args)
        {
            int length = int.Parse(Console.ReadLine());
            string input;
            var listOfOnes = new List<int>();
            var listOfIndex = new List<int>();
            var listOfSums = new List<int>();
            List<int[]> data = new List<int[]>();
            int found1 = 1;
            int foundMax = 0;
            int indexFound = 0;
            int[] arr = new int[length];
            
            do
            {
                input = Console.ReadLine();
                if (input != "Clone them!")
                {
                    arr = input
                          .Split('!', StringSplitOptions.RemoveEmptyEntries)
                          .Select(int.Parse)
                          .ToArray();
                    data.Add(arr);
                    int sum = arr.Sum();
                    listOfSums.Add(sum);
                    for (int i = 0; i < arr.Length-1; i++)
                    {
                        if(arr[i]==arr[i+1]&arr[i]!=0)
                        {
                            found1++;
                        }
                        else
                        {
                            found1 = 1;
                        }
                        if(found1>foundMax)
                        {
                            foundMax = found1;
                            indexFound = i + 2 - foundMax;
                        }
                    }
                    
                    listOfOnes.Add(foundMax);
                    listOfIndex.Add(indexFound);
                    found1 = 1;
                    indexFound = 0;
                    foundMax = 0;
                }
            } while (input != "Clone them!");

            int maxOnes = listOfOnes.Max();
            
           
            
            List<int[]> newData = new List<int[]>(data);

            for (int i = 0; i < listOfOnes.Count; i++)
            {
                if(listOfOnes[i]!=maxOnes)
                {
                    listOfOnes.RemoveAt(i);
                    listOfSums.RemoveAt(i);
                    listOfIndex.RemoveAt(i);
                    newData.RemoveAt(i);
                    i--;
                }
            }
            int minIndex = listOfIndex.Min();
            for (int i = 0; i < listOfIndex.Count; i++)
            {
                if(listOfIndex[i]>minIndex)
                {
                    listOfOnes.RemoveAt(i);
                    listOfSums.RemoveAt(i);
                    listOfIndex.RemoveAt(i);
                    newData.RemoveAt(i);
                    i--;
                }
            }
            int maxSum = listOfSums.Max();
            for (int i = 0; i < listOfSums.Count; i++)
            {
                if (listOfSums[i]<maxSum)
                {
                    listOfOnes.RemoveAt(i);
                    listOfSums.RemoveAt(i);
                    listOfIndex.RemoveAt(i);
                    newData.RemoveAt(i);
                    i--;
                }
            }

            int sample = 0;
            string toPrint = String.Empty;
            for (int i = 0; i < data.Count; i++)
            {
                for (int j = 0; j < newData.Count; j++)
                {
                    if(data[i]==newData[j])
                        for (int k = 0; k < newData[j].Length; k++)
                        {
                            
                            toPrint += (newData[j][k] + " ").ToString();
                            sample = i+1;
                        }
                    
                }
            }
            Console.WriteLine("Best DNA sample {0} with sum: {1}.", sample, listOfSums[0]);
            toPrint = toPrint.Remove(toPrint.Length - 1);
            Console.WriteLine(toPrint);

            

        }
    }
}
 

Тагове:
0
C# Fundamentals 09/12/2020 15:44:59
MartinBG avatar MartinBG 4803 Точки

Задачата не минава в Judge заради проблеми при форматирането или в логиката преди това, но честно казано не съм търсил къде точно е проблема.

 

Заменете този код:

            int sample = 0;
            string toPrint = String.Empty;
            for (int i = 0; i < data.Count; i++)
            {
                for (int j = 0; j < newData.Count; j++)
                {
                    if(data[i]==newData[j])
                        for (int k = 0; k < newData[j].Length; k++)
                        {
                            
                            toPrint += (newData[j][k] + " ").ToString();
                            sample = i+1;
                        }
                    
                }
            }
            Console.WriteLine("Best DNA sample {0} with sum: {1}.", sample, listOfSums[0]);
            toPrint = toPrint.Remove(toPrint.Length - 1);
            Console.WriteLine(toPrint);

С този:

            Console.WriteLine("Best DNA sample {0} with sum: {1}.", data.IndexOf(newData[0]) + 1, listOfSums[0]);
            Console.WriteLine(string.Join(" ", newData[0]));

И решението ще вземе 100 точки в Judge.

1
09/12/2020 20:51:40
adelina_t avatar adelina_t 2 Точки

Благодаря!

1
Можем ли да използваме бисквитки?
Ние използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Можете да се съгласите с всички или част от тях.
Назад
Функционални
Използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Използваме „сесийни“ бисквитки, за да Ви идентифицираме временно. Те се пазят само по време на активната употреба на услугите ни. След излизане от приложението, затваряне на браузъра или мобилното устройство, данните се трият. Използваме бисквитки, за да предоставим опцията „Запомни Ме“, която Ви позволява да използвате нашите услуги без да предоставяте потребителско име и парола. Допълнително е възможно да използваме бисквитки за да съхраняваме различни малки настройки, като избор на езика, позиции на менюта и персонализирано съдържание. Използваме бисквитки и за измерване на маркетинговите ни усилия.
Рекламни
Използваме бисквитки, за да измерваме маркетинг ефективността ни, броене на посещения, както и за проследяването дали дадено електронно писмо е било отворено.