蓝桥杯——试题 算法训练 Yaroslav and Algorithm

时间:2023-03-10 07:23:48
蓝桥杯——试题 算法训练 Yaroslav and Algorithm

试题 算法训练 Yaroslav and Algorithm

资源限制

时间限制:100ms 内存限制:128.0MB

问题描述

  (这道题的数据和SPJ已完工,尽情来虐吧!)

  Yaroslav喜欢算法。我们将描述一个他最喜欢的算法。

  1.这个算法接受一个字符串作为输入。我们设这个输入字符串为a。

  2.这个算法由一些命令组成。i号命令的形式为"s[i]>>w[i]"或"s[i]<>w[i]",其中s[i]和w[i]是长度不超过7的字符串(可以为空),由数字

或字符"?"组成。

  3.这个算法每次寻找一个编号最小的命令i,使得s[i]是a的子串。如果没有找到这样的命令,那么整个算法终止。

  4.设找到的命令编号为k。在字符串a中,s[k]第一次出现的位置会被w[k]替换。如果这个命令形如"s[k]>>w[k]",那么这个算法继续执行(译注:

回到第3步)。否则,算法终止。

  5.算法的输出就是算法终止时字符串a的值。

  Yaroslav有一个n个正整数的集合,他需要一个这样的算法,且能够使每一个数加1。更正式地,如果我们把每个数看成一个十进制表示的字符串,

那么对于每个字符串独立地运行这个算法,这个算法需要输出一个输入串对应的数+1的字符串。

  帮帮他吧!

输入格式

  第一行包含一个整数n(集合中数的个数),接下来n行,每行包含一个正整数。

输出格式

  输出一个符合题意的算法(能够分别将每个数增加1)。第i行输出这个算法的第i个命令,不包含空格。

  你的算法将会对于每个输入运行一遍。你的输出会被认为是正确的,当且仅当:

  ·每行都是一个合法的命令(格式见题目描述)

  ·命令的条数不能超过50。

  ·算法需要对每个给出的数+1。

  ·为了得到结果,算法必须对于每个输入都执行不超过200步。

样例输入

2

10

79

样例输出

10<>11

79<>80

数据规模和约定

  1≤每个数≤10^25。共有20个测试点,对于第i个测试点,n=5i。

public class Main {
public static void main(String[] args) throws IOException {
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(input.readLine());
input.close();
StringBuilder[] arr = new StringBuilder[n];
for (int i = 0; i < n; i++) {
arr[i] = new StringBuilder("0" + input.readLine());
}
f(arr);
} public static void f(StringBuilder[] arr) {
for (int i = 0; i < arr.length; i++) {
// 将即将要操作的字符串用临时变量保存起来
StringBuilder temp = new StringBuilder(arr[i]);
int index = arr[i].length() - 1;
int a = Integer.parseInt(arr[i].substring(index, index + 1)) + 1; // 如果加+1超过9,且当前的index大于0就要进位给前面一位数
while (a > 9 && index > 0) {
// 进位之后,当前位置一定要变为0
arr[i].setCharAt(index, '0');
// 向前移动一位
index--;
// 进位
a = Integer.parseInt(arr[i].substring(index, index + 1)) + 1;
}
// 跳出了while循环,则表示此处以及此处之前都不需要进位了
arr[i].setCharAt(index, (char) (a + '0')); if ("0".equals(arr[i].substring(0, 1))) {
System.out.println(temp.substring(1) + "<>" + arr[i].substring(1));
} else {
System.out.println(temp.substring(1) + "<>" + arr[i]);
}
}
}
}