(测试点3、4两个超时了。若各位有复杂度更低的方法和思路,欢迎在评论区讨论。谢谢!)
1.题目如下:
“单身狗”是中文对于单身人士的一种爱称。本题请你从上万人的大型派对中找出落单的客人,以便给予特殊关爱。
输入格式:
输入第一行给出一个正整数 N(≤ 50 000),是已知夫妻/伴侣的对数;随后 N 行,每行给出一对夫妻/伴侣——为方便起见,每人对应一个
ID 号,为 5 位数字(从 00000 到 99999),ID 间以空格分隔;之后给出一个正整数 M(≤ 10
000),为参加派对的总人数;随后一行给出这 M 位客人的 ID,以空格分隔。题目保证无人重婚或脚踩两条船。
输出格式:
首先第一行输出落单客人的总人数;随后第二行按 ID 递增顺序列出落单的客人。ID 间用 1 个空格分隔,行的首尾不得有多余空格。
输入样例:
3
11111 22222
33333 44444
55555 66666
7
55555 44444 10000 88888 22222 11111 23333
输出样例:
5
10000 23333 44444 55555 88888
代码长度限制 16 KB 时间限制 200 ms 内存限制 64 MB
2.代码如下:
package pat_1065;
import java.util.HashMap;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
public class testPractice1065 {
public static void main(String[] args) {
try {
BufferedReader bf1=new BufferedReader(new InputStreamReader(System.in));
int companyNumber=Integer.parseInt(bf1.readLine());
String[] company=new String[companyNumber];
HashMap<String,String> company1=new HashMap<String,String>();
//这里使用HashMap,将每个人的情侣都录入进去,方便查找判断
for(int i=0;i<companyNumber;i++) {
company[i]=bf1.readLine();
company1.put(company[i].split(" ")[1], company[i].split(" ")[0]);//两个人都要录
company1.put(company[i].split(" ")[0], company[i].split(" ")[1]);
}
int partyNumber=Integer.parseInt(bf1.readLine());
ArrayList<String> partyPlayer=new ArrayList<String>();
String str1=bf1.readLine();
for(int i=0;i<partyNumber;i++) {
partyPlayer.add(str1.split(" ")[i]);
}
ArrayList<String> bachelor=new ArrayList<String>();
int temp=0;
for(int i=0;i<partyNumber;i++) {
//遍历参加party的人,看在HashMap种是否有对象录入
if(partyPlayer.indexOf(company1.get(partyPlayer.get(i)))==-1) {
bachelor.add(partyPlayer.get(i));
temp++;
}
}
//排序
Collections.sort(bachelor);
System.out.println(temp);
for(int i=0;i<temp;i++) {
if(i!=temp-1) {
System.out.print(bachelor.get(i)+" ");
}
else {
System.out.print(bachelor.get(i));
}
}
}catch(Exception ex) {
ex.printStackTrace();
}
}
}