按比例切分组合数值(洛谷P1008、P1618题解,Java语言描述)
生活随笔
收集整理的這篇文章主要介紹了
按比例切分组合数值(洛谷P1008、P1618题解,Java语言描述)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
P1008題目要求
P1008題目鏈接
P1618題目要求
P1618題目鏈接
分析
P1618是P1008的增強版,使得一個水題沒有那么水了,不過還是挺簡單的。
其實judge()函數的話,兩題可以共用,就是判斷一下是不是“槽位已滿”而已。如果還有坑位就占上,就這么個思路。
main()里的基本流程的話,其實沒什么特別的算法,暴力枚舉就行。
第一題的話由于是1:2:3,所以下限也就123,上限也就333,在里面遍歷能縮小范圍。
第二題的話由于是A:B:C,所以不能自設上下限,從1~999即可,極限暴力就好啦,但是必須在A,B,C那里設限,全部要在100 ~ 999之間,這個很重要,在judge()之前保證數據范圍可以避免RE(數組越界)。
P1618第一次提交WA了一個樣例:
我獲取了測試數據5:
in
123 456 789
out
123 456 789
其實就是上面說的問題,不應該在for循環設限,而是應該在judge()之前設限。
P1008~AC代碼(Java語言描述)
public class Main {private static byte[] arr = new byte[9];public static void main(String[] args) {for (int i = 123; i < 333; i++) {arr = new byte[9];int two = 2*i, three = 3*i;if (judge(i) && judge(two) && judge(three)) {System.out.println(i + " " + two + " " + three);}}}private static boolean judge(int i) {int a = i / 100;int b = (i % 100) / 10;int c = i - a*100 - b*10;if (b == 0 || c == 0 || a == b || a == c || b == c || arr[a-1] == 1 || arr[b-1] == 1 || arr[c-1] == 1) {return false;}arr[a-1] = arr[b-1] = arr[c-1] = 1;return true;}}P1618~AC代碼(Java語言描述)
import java.util.Scanner;public class Main {private static byte[] arr = new byte[9];private static boolean judge(int i) {int a = i / 100;int b = (i % 100) / 10;int c = i - a*100 - b*10;if (b == 0 || c == 0 || a == b || a == c || b == c || arr[a-1] == 1 || arr[b-1] == 1 || arr[c-1] == 1) {return false;}arr[a-1] = arr[b-1] = arr[c-1] = 1;return true;}public static void main(String[] args) {Scanner scanner = new Scanner(System.in);int a = scanner.nextInt(), b = scanner.nextInt(), c = scanner.nextInt();scanner.close();boolean flag = false;for (int i = 1; i < 1000; i++) {arr = new byte[9];int one = a*i, two = b*i, three = c*i;if (one > 100 && one < 1000 && two > 100 && two < 1000 && three > 100 && three < 1000&& judge(one) && judge(two) && judge(three)) {flag = true;System.out.println(one + " " + two + " " + three);}}if (!flag) {System.out.println("No!!!");}}} 創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的按比例切分组合数值(洛谷P1008、P1618题解,Java语言描述)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【算法分析与设计】埃氏筛素数算法
- 下一篇: 【数据结构与算法】AVL树核心算法的Ja