題目:http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1361
這題很麻煩,可能是我寫法不好orz....
import java.util.*;
import java.lang.*;
public class Main{
static String[] data = new String[2000];
static String[] country = new String[2000];
static int[] total = new int[2000];
static int index=-1;
static int num=index+1;
static boolean change=false;
public static void main(String[] args) {
Scanner k = new Scanner(System.in);
int n = k.nextInt();
k.nextLine();
while(n--!=0){
insert(k.nextLine());//一次讀入國別+姓名
}
sort();
print();
}
public static void insert(String Data){
boolean finded=false;
if(index==-1){//第一次就進入,為了解決nullpointer(runtimeError)問題,因為陣列裡都還沒有資料
finded=true;
index++;
data[index]=Data;
country[index]=Data.split(" ")[0];
total[index]++;
num++;
}
else{
for(int i=0 ; i<num ;i++){//找有沒有重複的輸入資料(國別+姓名)
if(data[i].equals(Data)){
finded=true;
break;
}
}
}
if(!finded){//如果都沒有重複就進入紀錄程序
boolean newIn = true;//是否要新增國家
for(int i=0 ; i<num ;i++){//找到同個國別就+1總人數,且不打算新增國別
if(country[i].equals(Data.split(" ")[0])){
newIn=false;
total[i]++;
}
}
if(newIn){//如果找不到同個國別就新增一筆國別+總人數
index++;
data[index]=Data;
country[index]=Data.split(" ")[0];
total[index]++;
num++;
}
}
}
public static void sort(){//根據字母順序排列國家
for(int i=0 ; i<num ;i++){
for(int j=i+1 ; j<num ;j++){
get(country[i],country[j],0);
if(change){
String tempCountry=country[i];
country[i]=country[j];
country[j]=tempCountry;
int tempTotal=total[i];
total[i]=total[j];
total[j]=tempTotal;
}
}
}
}
public static void print(){//將結果印出來
for(int i=0 ; i<num ;i++){
//if(i==num-1)
//System.out.print(country[i]+" "+total[i]);
//else
System.out.println(country[i]+" "+total[i]);
}
}
public static void get(String a , String b,int index){//遞迴依序比較字元ASCII碼大小
if((int)a.charAt(index)==(int)b.charAt(index)){
get(a,b,++index);
}
else if((int)a.charAt(index)>(int)b.charAt(index)){
change=true;
}
else
change=false;
}
}
沒有留言:
張貼留言