2756. Lucky Transformation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya has a number consisting of n digits without leading zeroes. He represented it as an array of digits without leading zeroes. Let's call it d. The numeration starts with 1, starting from the most significant digit. Petya wants to perform the following operation k times: find the minimum x (1≤x<n) such that dx=4 and dx+1=7, if x is odd, then to assign dx=dx+1=4, otherwise to assign dx=dx+1=7. Note that if no x was found, then the operation counts as completed and the array doesn't change at all.
You are given the initial number as an array of digits and the number k. Help Petya find the result of completing k operations.
The first line contains two integers n and k (1≤n≤105,0≤k≤109) − the number of digits in the number and the number of completed operations. The second line contains n digits without spaces representing the array of digits d, starting with d1. It is guaranteed that the first digit of the number does not equal zero.
In the single line print the result without spaces − the number after the k operations are fulfilled.
7 4
4727447
4427477
4 2
4478
4478
In the first sample the number changes in the following sequence: 4727447→4427447→4427477→4427447→4427477.
In the second sample: 4478→4778→4478.
说明:唉,这个题失败了,运行时间过长!虽然想到了有出现循环的可能,但是明明已经有了优化,可是还是不能通过,有点郁闷。
// time out import java.util.Scanner; public class Test2756 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int k = sc.nextInt(); sc.nextLine(); String str = sc.nextLine(); char[] chArr = str.toCharArray(); // 现在的问题就是,如果k特别大,又存在要交换的数那我无话可说,但是如果存在的要交换的数是这样的呢? // 447——>477——>447——>477看到没有,这样的一个循环,那么我们还可以再优化 for (int i = 0; i < k; i++) { boolean flag = true; for (int j = 0; j < n - 1; j++) { if ((chArr[j] == '4') && (chArr[j + 1] == '7')) { if (j % 2 == 0) { chArr[j] = '4'; chArr[j + 1] = '4'; if (j < chArr.length - 2 && chArr[j + 2] == '7') { if ((k - i) % 2 == 0) { chArr[j + 1] = '7'; chArr[j + 2] = '7'; break; } } } else { chArr[j] = '7'; chArr[j + 1] = '7'; } flag = false; break; } } if (flag) { break; } } for (int y = 0; y < chArr.length; y++) { System.out.print(chArr[y]); } System.out.println(); } }
未优化:
// time out import java.util.Scanner; public class Test2756 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int k = sc.nextInt(); sc.nextLine(); String str = sc.nextLine(); for (int i = 0; i < k; i++) { if (str.indexOf("47") != -1) { int num = str.indexOf("47"); if (num % 2 == 0) { str = str.replaceFirst("47", "44"); } else { str = str.replaceFirst("47", "77"); } } System.out.println(str); } } }