有n个格子,从左到右放成一排,编号为1-n。
共有m次操作,有3种操作类型:
1.修改一个格子的权值,
2.求连续一段格子权值和,
3.求连续一段格子的最大值。
对于每个2、3操作输出你所求出的结果。
第一行2个整数n,m。
接下来一行n个整数表示n个格子的初始权值。
接下来m行,每行3个整数p,x,y,p表示操作类型,p=1时表示修改格子x的权值为y,p=2时表示求区间[x,y]内格子权值和,p=3时表示求区间[x,y]内格子最大的权值。
有若干行,行数等于p=2或3的操作总数。
每行1个整数,对应了每个p=2或3操作的结果。
对于20%的数据n <= 100,m <= 200。
对于50%的数据n <= 5000,m <= 5000。
对于100%的数据1 <= n <= 100000,m <= 100000,0 <= 格子权值 <= 10000。
示例代码:
import java.util.ArrayList;
import java.util.Scanner;
public class 操作格子 {
public static int n, m, p, x, y;
public static int arr[];
public static ArrayList<Integer> list = new ArrayList<Integer>();
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
m = sc.nextInt();
arr = new int[n];
for(int i=0; i<n; i++) {
arr[i] = sc.nextInt();
}
for (int i = 0; i < m; i++) {
p = sc.nextInt();
x = sc.nextInt();
y = sc.nextInt();
operate(p, x, y);
}
for(int i=0; i<list.size(); i++) {
System.out.println(list.get(i));
}
sc.close();
}
private static void operate(int p, int x, int y) {
//System.out.println(p + "," + x + "," + y);
if (p == 1) {
arr[x - 1] = arr[y - 1];
} else if (p == 2) {
int result = 0;
for(int i=x-1; i<=y-1; i++) {
result += arr[i];
}
list.add(result);
} else if (p == 3) {
int max = Integer.MIN_VALUE;
for(int i=x-1; i<=y-1; i++) {
if(arr[i] > max) {
max = arr[i];
}
}
list.add(max);
}
}
}
原文地址:http://blog.csdn.net/tracysilocean/article/details/45014359