【题目】Problem B.字符串操作

Problem B.字符串操作

题目描述
给定一个长度为n (n>=1)的字符串序列,标记为[a1,a2…an],在字符串序列上定义以下5种操作类型,分别标号为1,2,3,4,5,同时l和r分别表示al​和ar​ 的下标,len 表示需要操作的子序列长度。操作定义如下:
1 l r — 将区间[al​, ar​]内的元素逆序。
2 l r len — 分别从al​和ar​元素开始,互换len个元素
3 l r x — 将区间[al​, ar​] 内的元素统一替换成x
4 l r — 将区间[al​, ar​] 内的元素按升序排序
5 l r — 计算区间[al​, ar​] 内的元素和,并输出元素和

输入格式
第一行输入n和m,表示字符串序列长度n和操作命令数m,
第二行输入n个整数构成字符串序列,在第三行及之后各行(共计m行)中,每行输入一个操作类型命令。

输出格式
输出每次的第5种操作类型的结果

Example
Inputs

9 8
1 2 3 4 5 6 7 8 9
1 4 8
5 7 9
2 2 5 3
5 5 9
3 5 8 3
4 3 8
5 7 9
5 1 9

Outputs
18
26
20
40

解答:

import java.util.Arrays;
import java.util.Scanner;
/*
Problem B.字符串操作
题目描述
给定一个长度为n (n>=1)的字符串序列,标记为[a1,a2...an],在字符串序列上定义以下5种操作类型,分别标号为1,2,3,4,5,同时l和r分别表示al​和ar​ 的下标,len 表示需要操作的子序列长度。操作定义如下:
1 l r	— 将区间[al​, ar​]内的元素逆序。
2 l r len — 分别从al​和ar​元素开始,互换len个元素
3 l r x — 将区间[al​, ar​] 内的元素统一替换成x
4 l r — 将区间[al​, ar​] 内的元素按升序排序
5 l r — 计算区间[al​, ar​] 内的元素和,并输出元素和
输入格式
第一行输入n和m,表示字符串序列长度n和操作命令数m,
第二行输入n个整数构成字符串序列,在第三行及之后各行(共计m行)中,每行输入一个操作类型命令。。
输出格式
输出每次的第5种操作类型的结果
Example
Inputs
9 8
1 2 3 4 5 6 7 8 9
1 4 8
5 7 9
2 2 5 3
5 5 9
3 5 8 3
4 3 8
5 7 9
5 1 9
Outputs
18
26
20
40
*/
public class Test{
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		while(scanner.hasNext()) {
			int n = scanner.nextInt();
			int commond = scanner.nextInt();
			int[] com = new int[n];
			for(int i = 0; i < n; i++) com[i] = scanner.nextInt();
			for(int i = 0; i < commond; i++) {
				int choice = scanner.nextInt();
				if(choice == 1) {
					int l = scanner.nextInt() - 1, r = scanner.nextInt() - 1;
					while(l < r) {
						int temp = com[l];
						com[l] = com[r];
						com[r] = temp;
						l++;
						r--;
					}
				}else if(choice == 2) {
					int l = scanner.nextInt() - 1, r = scanner.nextInt() - 1, len = scanner.nextInt();
					for(int j = 0; j < len; j++) {
						int temp = com[l];
						com[l] = com[r];
						com[r] = temp;
						l++;
						r++;
					}
				}else if(choice == 3) {
					int l = scanner.nextInt() - 1, r = scanner.nextInt() - 1, x = scanner.nextInt();
					for(int j = l; j <= r; j++) com[j] = x;
				}else if(choice == 4) {
					int l = scanner.nextInt() - 1, r = scanner.nextInt() - 1;
					Arrays.sort(com, l, r + 1);
				}else if(choice == 5) {
					int l = scanner.nextInt() - 1, r = scanner.nextInt() - 1, sum = 0;
					for(int j = l; j <= r; j++) sum += com[j];
					System.out.println(sum);
				}
			}
		}
	}	
}
发布了233 篇原创文章 · 获赞 254 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/weixin_44485744/article/details/104997242