ACM一种排序题8Java实现

来源:互联网 发布:兰州大学 知乎 编辑:程序博客网 时间:2024/05/16 00:33
描述
现在有很多长方形,每一个长方形都有一个编号,这个编号可以重复;还知道这个长方形的宽和长,编号、长、宽都是整数;现在要求按照一下方式排序(默认排序规则都是从小到大);

1.按照编号从小到大排序

2.对于编号相等的长方形,按照长方形的长排序;

3.如果编号和长都相同,按照长方形的宽排序;

4.如果编号、长、宽都相同,就只保留一个长方形用于排序,删除多余的长方形;最后排好序按照指定格式显示所有的长方形;
输入
第一行有一个整数 0<n<10000,表示接下来有n组测试数据;
每一组第一行有一个整数 0<m<1000,表示有m个长方形;
接下来的m行,每一行有三个数 ,第一个数表示长方形的编号,

第二个和第三个数值大的表示长,数值小的表示宽,相等
说明这是一个正方形(数据约定长宽与编号都小于10000);
输出
顺序输出每组数据的所有符合条件的长方形的 编号 长 宽
样例输入
181 1 11 1 11 1 21 2 11 2 22 1 12 1 22 2 1
样例输出
1 1 11 2 11 2 22 1 12 2 1

思路

把多组长方形的编号、长、宽放入一个三维数组中,然后按照规则对每组长方形进行排序。

代码:

import java.util.*;public class Main {public static void main(String[] args){Scanner input = new Scanner(System.in);int row = 0;int length = 0;int wide = 0;int code = 0;row = input.nextInt(); //总共有几组int[][][] rect = new int[row][][];for(int index = 0; index < row; index++){int num = input.nextInt(); //每一组有多少长方形rect[index] = new  int[num][3];for(int i = 0; i < num; i++) //输入一组长方形的数据{ code = input.nextInt(); int a = input.nextInt(); int b = input.nextInt(); if(a > b) { length = a; wide = b; } else { length = b; wide = a; } rect[index][i][0] = code; rect[index][i][1] = length; rect[index][i][2] = wide; }}rectsort(rect);}public static int[][][] rectsort(int a[][][]){for(int i  = 0; i < a.length; i++ ){for(int i1 = 0; i1 < a[i].length; i1++){int[][] temp = new int[1][3]; for(int i2 = i1+1; i2 < a[i].length; i2++){if(a[i][i1][0] > a[i][i2][0]){temp[0] = a[i][i1];a[i][i1] = a[i][i2];a[i][i2] = temp[0];}else if(a[i][i1][0] == a[i][i2][0]){if(a[i][i1][1] > a[i][i2][1]){temp[0] = a[i][i1];a[i][i1] = a[i][i2];a[i][i2] = temp[0];}else if(a[i][i1][1] == a[i][i2][1]){if(a[i][i1][2] > a[i][i2][2]){temp[0] = a[i][i1];a[i][i1] = a[i][i2];a[i][i2] = temp[0];}else if (a[i][i1][2] == a[i][i2][2]){a[i][i1][0] = 0;a[i][i1][1] = 0;a[i][i1][2] = 0;}}}}}}for(int i  = 0; i < a.length; i++ ){for(int i1 = 0; i1 < a[i].length; i1++){ if(!(a[i][i1][0] == 0)){System.out.print(a[i][i1][0] + " ");System.out.print(a[i][i1][1] + " ");System.out.println(a[i][i1][2]);}}}return a;}}