JAVA中的结构体排序 【java】【基础】,
分享于 点击 32959 次 点评:49
JAVA中的结构体排序 【java】【基础】,
这里我们来举几个例题来解决这个问题
例一:HRBUST 1095 最麻烦了
最麻烦了
| ||||||
Description | ||||||
有道是:“勤能补拙,熟能生巧;细节决定成败,态度决定一切,现象决定本质,现在决定未来;是游戏的围墙,最麻烦了。” | ||||||
Input | ||||||
对于每组测试数据: | ||||||
Output | ||||||
对于每组测试数据: | ||||||
Sample Input | ||||||
3 | ||||||
Sample Output | ||||||
1000000000 50 100 |
这题是一题典型的结构体排序题:
上代码:
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
import java.util.*;
class shu ///创建类
{
int acm;
int mon;
int rp;
}
class cmp implements Comparator<shu> {
public int compare(shu A, shu B) ///降序排序
{
if(A.acm==B.acm)
{
if(A.mon==B.mon)
{
if(A.rp<B.rp)
{
return 1;
}
else if(A.rp==B.rp)
{
return 0;
}
else
{
return -1;
}
}
else
{
if(A.mon<B.mon)
{
return 1;
}
else if(A.mon==B.mon)
{
return 0;
}
else
{
return -1;
}
}
}
else
{
if(A.acm<B.acm)
{
return 1;
}
else if(A.acm==B.acm)
{
return 0;
}
else
{
return -1;
}
}
}
}
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
shu num[] = new shu[1005];///创建类数组
int n;
n = in.nextInt();
for (int i = 0; i < n; i++) {
num[i]=new shu();///这个地方容易漏
num[i].acm = in.nextInt();
num[i].mon = in.nextInt();
num[i].rp = in.nextInt();
}
Arrays.sort(num, 0, n, new cmp());
for (int i = 0; i < n; i++) {
System.out.println(num[i].acm+" "+num[i].mon+" "+num[i].rp);
}
}
}
}
//int compare(Object o1, Object o2) 返回一个基本类型的整型
//如果要按照升序排序,
//则o1 小于o2,返回-1(负数),相等返回0,01大于02返回1(正数)
//如果要按照降序排序
// 则o1 小于o2,返回1(正数),相等返回0,01大于02返回-1(负数)
//
不过这题中没有字符串的输入与输出。。。
我们这里补充一题带上字符串输入的题::HRBUST 1023 JiaoZhu and CS
在上代码前补充个函数的用法。
java中的compareto方法,返回参与比较的前后两个字符串的asc码的差值。通过这个函数,我们可以实现字符串的字典序排序。
上代码:(这个代码提交会超时!!!!!!!!!!!!!)
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
import java.util.*;
class shu ///创建类
{
String name;///比较时用String
int mon;
int hunt;
}
class cmp implements Comparator<shu> {
public int compare(shu A, shu B)
{
if(A.hunt==B.hunt)
{
if(A.mon==B.mon)
{
int flag=(A.name).compareTo(B.name);///按字典序排序
if(flag==0)
{
return 0;
}
else if(flag<0)
{
return -1;
}
else
{
return 1;
}
}
else
{
if(A.mon==B.mon)
{
return 0;
}
else if(A.mon<B.mon)
{
return -1;
}
else
{
return 1;
}
}
}
else
{
if(A.hunt==B.hunt)
{
return 0;
}
else if(A.hunt<B.hunt)
{
return 1;
}
else
{
return -1;
}
}
}
}
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
shu num[] = new shu[100005];///创建类数组
int n;
n = in.nextInt();
for (int i = 0; i < n; i++) {
num[i]=new shu();///这个地方容易漏
num[i].name=in.next();
num[i].hunt=in.nextInt();
num[i].mon=in.nextInt();
}
Arrays.sort(num, 0, n, new cmp());
for (int i = 0; i < n; i++) {
System.out.println(num[i].name);
}
}
}
}
大约就是酱紫。。♪(^∇^*)
相关文章
- 暂无相关文章
用户点评