图片来源网上。
例子:
输入:
2
10
open libc.so
open libm.so
open libdl.so
dup 2
dup2 0 2
close 0
query 1
query 2
query 3
open log.txt
10
open output.txt
dup2 0 1000000
close 0
open output2.txt
dup2 0 100000
close 0
open 1.txt
dup 100000
query 1
query 0
输出:
0
1
2
3
libm.so
libc.so
libdl.so
0
0
0
0
1
output2.txt
1.txt
思路:这道题我只A出来50%,而且显示部分输入超时,原因应该是本来查找下一个最小的可用的文件描述符我是暴力搜索的,也就是每次都从0开始搜索,有哪个数字还没有使用过,就返回它,对应下面的find方法。后面改了一下,使用minsearch来保存最小的可用文件描述符。因此,现在改了之后也不知道到底能A多少,但是50%是至少的。
public static TreeMap<Integer,String> map;
public static List<String> res=new ArrayList<>();
public static int minsearch;
public static void process(String str){
String[] strs=str.split(" ");
minsearch=0;//保存当前的最小可搜索的起始点
if(strs[0].equals("open")){
int index=find();//找到可以用的描述符
map.put(index, strs[1]);
res.add(String.valueOf(index) );
minsearch=index+1;
}else if(strs[0].equals("dup")){
int index=find();
String wenjian=map.get(Integer.valueOf(strs[1]));
map.put(index, wenjian);
res.add(String.valueOf(index));
}else if(strs[0].equals("dup2")){
String wenjian=map.get(Integer.valueOf(strs[1]));
map.put(Integer.valueOf(strs[2]), wenjian);
}else if(strs[0].equals("close")){
map.remove(Integer.valueOf(strs[1]));
minsearch=Math.min(minsearch, Integer.valueOf(strs[1]));
}else {
String save=map.get(Integer.valueOf(strs[1]));
res.add(save);
}
}
public static int find(){
while(minsearch>=0){
if(!map.containsKey(minsearch)){
return minsearch;
}else
minsearch++;
}
return minsearch;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
while(sc.hasNext()){
int T=sc.nextInt();
sc.nextLine();
for(int i=0;i<T;i++){//T次查询
int N=sc.nextInt();
sc.nextLine();
map=new TreeMap<>();
for(int j=0;j<N;j++){
String str=sc.nextLine();
process(str);
}
}
for(String a:res){
System.out.println(a);
}
}
}