1. 程式人生 > >PAT L1-005. 考試座位號 Java超時解決方案

PAT L1-005. 考試座位號 Java超時解決方案

每個PAT考生在參加考試時都會被分配兩個座位號,一個是試機座位,一個是考試座位。正常情況下,考生在入場時先得到試機座位號碼,入座進入試機狀態後,系統會顯示該考生的考試座位號碼,考試時考生需要換到考試座位就座。但有些考生遲到了,試機已經結束,他們只能拿著領到的試機座位號碼求助於你,從後臺查出他們的考試座位號碼。

輸入格式:

輸入第一行給出一個正整數N(<=1000),隨後N行,每行給出一個考生的資訊:“准考證號 試機座位號 考試座位號”。其中准考證號由14位數字組成,座位從1到N編號。輸入保證每個人的准考證號都不同,並且任何時候都不會把兩個人分配到同一個座位上。

考生資訊之後,給出一個正整數M(<=N),隨後一行中給出M個待查詢的試機座位號碼,以空格分隔。

輸出格式:

對應每個需要查詢的試機座位號碼,在一行中輸出對應考生的准考證號和考試座位號碼,中間用1個空格分隔。

輸入樣例:
4
10120150912233 2 4
10120150912119 4 1
10120150912126 1 3
10120150912002 3 2
2
3 4
輸出樣例:
10120150912002 2
10120150912119 1

我用Java 一直過不了 我的Java程式碼如下:


import java.util.*;


public class Main {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
			Scanner sc = new Scanner(System.in);
			
			int n = Integer.parseInt(sc.nextLine());
			
			String strr[] = new String[n+1];
			String strr1[][] = new String[n+1][];
			String temp = new String();
			String temp1[] = new String [3];
			for(int v = 0;v < n;v ++){
				temp = sc.nextLine();
				temp1= temp.split(" ");//
			
				strr1[Integer.parseInt(temp1[1])] = temp1;
			}
			int m = sc.nextInt();
			int m1[] = new int[m];
			
			for(int i = 0;i < m;i ++){
				int tem = sc.nextInt();
				System.out.println(strr1[tem][0]+" "+strr1[tem][2]);
			}
	}
}

估測原因是Scanner超時導致。

我用C++一次就過了 超級Nice  此外這道題不需要使用Sort修改函式做 我巧妙地用第二列的試機座位號為進行陣列下標確定的依據,整個演算法複雜度為O(n)。程式碼如下:

#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <iostream>
using namespace std;
typedef struct people{
    char a[15];
    int b;
    int c;
}p;



int main(){
  int n;

 scanf("%d",&n);
 struct people Peo[n+1];
  for(int i = 0;i < n;i ++){
    int tempb;
    int tempc;
    char strtemp[15];

    scanf("%s %d %d",strtemp,&tempb,&tempc);
    memset(Peo[tempb].a,'\0',sizeof(char)*15);
    strcat(Peo[tempb].a,strtemp);

    Peo[tempb].b=tempb;
    Peo[tempb].c=tempc;

  }

    int m;
    cin>>m;
    int d[m];
    for(int i = 0;i < m;i ++){
        cin>>d[i];
    }
    for(int i = 0;i < m;i ++){
        printf("%s %d\n",Peo[d[i]].a,Peo[d[i]].c);
    }
    return 0;
}