经此一役小红所向无敌
算法原理
模拟,就是模拟战役过程,先同时攻击,然后互相攻击,攻击完之后看有人死了没,死了再做对应操作
注意点
该题数据量还是比较大的,要开long
代码
import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
long res = 0;
long a = scan.nextInt(), h = scan.nextInt(), b = scan.nextInt(),
k = scan.nextInt();
while (h >= 0 || k >= 0) {
h -= b;
k -= a;
res += a + b;
if (h <= 0 && k <= 0) { //两个人都死了
break;
} else if (h <= 0 && k > 0) { //对立死了
res += b * 10;
break;
} else if (h > 0 && k <= 0) { //光死了
res += a * 10;
break;
}
}
System.out.println(res);
}
}
连续子数组最大和
算法原理
线性dp
- dp[i]表示到i位置的子数组最大和
- dp[i]有两种情况,一种前面子数组如果为负数的话,那么就应该从当前位置重新开始计算子数组;如果前面为正数,就接着来,因此状态转移方程:dp[i] = Math.max(dp[i-1], 0) + nums[i-1];
- 结果就维持每一次res和dp[i]的最大值
代码
import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int[] nums = new int[n];
long[] dp = new long[n + 1];
//res不能为0,有可能有负数结果情况
long res = Integer.MIN_VALUE;
for(int i = 0; i < n; i++) nums[i] = scan.nextInt();
for(int i = 1; i <= n; i++) {
dp[i] = Math.max(dp[i-1], 0) + nums[i-1];
res = Math.max(res, dp[i]);
}
System.out.println(res);
}
}
非对称之美
算法原理
找规律,事实上有点类似贪心的想法,如果整个字符串不是回文串,那么最长的必定是它自己,如果整个字符串是回文串,那么实际上,最长的就是整个字符串长度-1,因为去掉其中一个字符就不是回文串了
注意点
有特殊情况,如果整个字符串都是同一个字符,那么就没有非回文字符串,即输出0
代码
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
boolean flg = false;
int res = 0;
String str = scan.next();
char[] chars = str.toCharArray();
for (int i = 1; i < chars.length; i++) {
if (chars[i] != chars[i-1]) {
flg = true;
break;
}
}
//不是相同字符串
if (flg) {
flg = false; //原字符串是回文字符串
int left = 0, right = str.length() - 1;
while (left < right) {
if (str.charAt(left) == str.charAt(right)) {
left++;
right--;
} else {
flg = true; //不是回文串
break;
}
}
if (flg) {
System.out.println(str.length());
} else System.out.println(str.length() - 1);
} else {
System.out.println(0);
}
}
}