题目来自牛客,
第一题
瞬间回到了十几年前,3个瓶子换饮料,可以借饮料还瓶子。
第一题我习惯直接打表,因为表中数据量不大直接模拟, 也可以用递推式。
从递推式中可以非常简单的总结出来通项公式。
import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
static int[] dp = new int[101];
static {
for (int i = 1; i < 101; i++) {
int res = 0;
int n = i;
while (n >= 3) {
res += n/3;
n = (n%3) + n/3;
}
if (n == 2) res++;
dp[i] = res;
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNextInt()) { // 注意 while 处理多个 case
int n = in.nextInt();
if (n == 0) break;
System.out.println(dp[n]);
}
}
}
import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
static int[] dp = new int[101];
static {
dp[0] = 0;
int more = 0;
for (int i = 1; i < 101; i++) {
more++;
if (more < 2) dp[i] = dp[i-1];
if (more == 2) dp[i] = dp[i-1] + 1;
if (more == 3) {
dp[i] = dp[i-1];
more = 1;
}
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNextInt()) { // 注意 while 处理多个 case
int n = in.nextInt();
if (n == 0) break;
System.out.println(dp[n]);
}
}
}
第二题
第二题排序, 然后从前向后输出。
import java.util.Arrays;
import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
int N = in.nextInt();
int[] nums = new int[N];
while (in.hasNextInt()) { // 注意 while 处理多个 case
for (int i = 0; i < N; i++) {
nums[i] = in.nextInt();
}
}
Arrays.sort(nums);
System.out.println(nums[0]);
for (int i = 1; i < N ; i++) {
if (nums[i] != nums[i-1])
System.out.println(nums[i]);
}
}
}
第三题
第三题写个hash表。 每次 res 左移4 然后加上hash表对应的数。
观察一下数据范围,甚至不需要long
import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
String s = in.nextLine();
char[] ss = s.toCharArray();
int n = s.length();
int[] hash = new int[256];
for (int i = '0'; i <= '9'; i++) hash[i] = i-'0';
for (int i = 'A'; i <= 'F'; i++) hash[i] = i-'A'+10;
int res = 0;
for (int i =2; i < n; i++) {
res <<= 4;
res += hash[ss[i]] ;
}
System.out.println(res);
}
}