Я действительно не могу понять проблему с моим кодом. ChatGPT и Клод не помогли разобраться в проблеме с моим кодом. Я прохожу большинство тестовых случаев и вполне укладываюсь в сроки, но есть некоторые тестовые примеры, которые я просто не могу пройти и не могу понять, почему. Я пытаюсь вычислить, сколько пар возможных лидеров существует в двух породах коров, основываясь на информации об их порядке из строки, где лидер породы определяется как тот, у кого в списке есть лидер другой породы и/или есть каждая корова своей породы в своем списке. Вот ссылка на проблему, это проблема лидеров за январь 2023 года:
https://usaco.org/index.php?page=viewproblem2&cpid=1275
и это мой код
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
/*
Notes To Self - There are a few cases.
Since you can't go backwards:
1) It is impossible for both cows to be leaders by having eachother:
- the second leader must contain all of its breed
- the first leader may contain the second and/or all of its breed
2) Any cow after the first instance of its breed cannot have all of its own breed in its list.
- This means any cow's leader cannot come after the first iteration of both breeds.
- So, there are only two candidates for the second leader.
What can be done is:
Find the first instance of the breeds.
If they contain the list of all of their own breeds, they are a possible leader
- at least one of the two first instances does this, guaranteed.
The number of pairs is then equal to the number of previous cows that contains at least one of the two possible leaders + a point if the two leaders contain eachother.
*/
int n = Integer.parseInt(br.readLine());
String cows = br.readLine();
int[] cowsEndIndex = new int[n];
TreeSet gIndex = new TreeSet();
TreeSet hIndex = new TreeSet();
StringTokenizer st = new StringTokenizer(br.readLine());
for(int i = 0; i < n; i++) {
cowsEndIndex = Integer.parseInt(st.nextToken())-1;
if(cows.charAt(i) == 'G') gIndex.add(i);
else hIndex.add(i);
}
int[] possibleLeaders = {-1, -1}; //G, H
if(cowsEndIndex[gIndex.first()] >= gIndex.last()) possibleLeaders[0] = gIndex.first();
if(cowsEndIndex[hIndex.first()] >= hIndex.last()) possibleLeaders[1] = hIndex.first();
int pairs = 0;
for(int i = 0; i < Math.max(possibleLeaders[0], possibleLeaders[1]); i++) {
if(possibleLeaders[1] != -1 && gIndex.contains(i)) {
if(cowsEndIndex >= possibleLeaders[1]) pairs++;
}
else if(possibleLeaders[0] != -1 && hIndex.contains(i)){
if(cowsEndIndex >= possibleLeaders[0]) pairs++;
}
}
if(possibleLeaders[0] != -1 && possibleLeaders[1] != -1 && !(cowsEndIndex[possibleLeaders[0]] >= possibleLeaders[1] || cowsEndIndex[possibleLeaders[1]] >= possibleLeaders[0])) pairs++;
pw.println(pairs);
br.close();
pw.close();
}
Подробнее здесь: https://stackoverflow.com/questions/798 ... rtial-pass
Логическая проблема с проблемой USACO, частичный проход ⇐ JAVA
Программисты JAVA общаются здесь
-
Anonymous
1767403862
Anonymous
Я действительно не могу понять проблему с моим кодом. ChatGPT и Клод не помогли разобраться в проблеме с моим кодом. Я прохожу большинство тестовых случаев и вполне укладываюсь в сроки, но есть некоторые тестовые примеры, которые я просто не могу пройти и не могу понять, почему. Я пытаюсь вычислить, сколько пар возможных лидеров существует в двух породах коров, основываясь на информации об их порядке из строки, где лидер породы определяется как тот, у кого в списке есть лидер другой породы и/или есть каждая корова своей породы в своем списке. Вот ссылка на проблему, это проблема лидеров за январь 2023 года:
https://usaco.org/index.php?page=viewproblem2&cpid=1275
и это мой код
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
/*
Notes To Self - There are a few cases.
Since you can't go backwards:
1) It is impossible for both cows to be leaders by having eachother:
- the second leader must contain all of its breed
- the first leader may contain the second and/or all of its breed
2) Any cow after the first instance of its breed cannot have all of its own breed in its list.
- This means any cow's leader cannot come after the first iteration of both breeds.
- So, there are only two candidates for the second leader.
What can be done is:
Find the first instance of the breeds.
If they contain the list of all of their own breeds, they are a possible leader
- at least one of the two first instances does this, guaranteed.
The number of pairs is then equal to the number of previous cows that contains at least one of the two possible leaders + a point if the two leaders contain eachother.
*/
int n = Integer.parseInt(br.readLine());
String cows = br.readLine();
int[] cowsEndIndex = new int[n];
TreeSet gIndex = new TreeSet();
TreeSet hIndex = new TreeSet();
StringTokenizer st = new StringTokenizer(br.readLine());
for(int i = 0; i < n; i++) {
cowsEndIndex[i] = Integer.parseInt(st.nextToken())-1;
if(cows.charAt(i) == 'G') gIndex.add(i);
else hIndex.add(i);
}
int[] possibleLeaders = {-1, -1}; //G, H
if(cowsEndIndex[gIndex.first()] >= gIndex.last()) possibleLeaders[0] = gIndex.first();
if(cowsEndIndex[hIndex.first()] >= hIndex.last()) possibleLeaders[1] = hIndex.first();
int pairs = 0;
for(int i = 0; i < Math.max(possibleLeaders[0], possibleLeaders[1]); i++) {
if(possibleLeaders[1] != -1 && gIndex.contains(i)) {
if(cowsEndIndex[i] >= possibleLeaders[1]) pairs++;
}
else if(possibleLeaders[0] != -1 && hIndex.contains(i)){
if(cowsEndIndex[i] >= possibleLeaders[0]) pairs++;
}
}
if(possibleLeaders[0] != -1 && possibleLeaders[1] != -1 && !(cowsEndIndex[possibleLeaders[0]] >= possibleLeaders[1] || cowsEndIndex[possibleLeaders[1]] >= possibleLeaders[0])) pairs++;
pw.println(pairs);
br.close();
pw.close();
}
Подробнее здесь: [url]https://stackoverflow.com/questions/79859485/logic-issue-with-usaco-problem-partial-pass[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия