Как прорваться от вложенного для l oop к его внешнему l oop? - PullRequest
0 голосов
/ 14 апреля 2020

Я пытаюсь решить проблему, в которой я должен найти 3 числа, которые складываются в число n для t числа дел.

Вот ограничения

Given four numbers N,A,B,C, find three numbers that sum up to N, with the following restrictions:

The first number must be an integer between 0 and A (inclusive)
The second number must be an integer between 0 and B (inclusive)
The third number must be an integer between 0 and C (inclusive)

I в настоящее время есть рабочее решение, однако мое решение распечатывает каждый возможный ответ вместо самого первого, который является правильным ответом. Как я могу вернуться к своему первому за-1 oop, когда найду самое первое решение?

Вот ссылка на проблему: https://dmoj.ca/problem/ac19p1

Вот мой код:

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner (System.in);
        int t = input.nextInt();

        for(int i=0;i<t;i++){

            int n = input.nextInt();
            int a = input.nextInt();
            int b = input.nextInt();
            int c = input.nextInt();

            if(n<0){
                System.out.println("-1");
            }
            else{
                for(int one=0; one<(a+1); one++){
                    for(int two=0; two<(b+1); two++){
                        for(int three=0; three<(c+1); three++){
                            if((one+two+three)==n){
                                System.out.println(one+" "+two+" "+three);
                                break;
                            }
                        }
                    }
                }

            }
        }
    }
}

Ввод:

1
100
100
53 
49

Правильное решение:

0 51 49

Мое текущее решение:

0 51 49
0 52 48
0 53 47
1 50 49
1 51 48
1 52 47
1 53 46
2 49 49
2 50 48
...

1 Ответ

2 голосов
/ 14 апреля 2020

Используйте метку.

      endItAll:
            for(int one=0; one<(a+1); one++){
                for(int two=0; two<(b+1); two++){
                    for(int three=0; three<(c+1); three++){
                        if((one+two+three)==n){
                            System.out.println(one+" "+two+" "+three);
                            break endItAll;
                        }
                    }
                }
            }

Дополнительная информация в руководстве: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html

...