-
Notifications
You must be signed in to change notification settings - Fork 86
/
Copy pathtyama_PKU1223(TLE).java
84 lines (77 loc) · 2.52 KB
/
tyama_PKU1223(TLE).java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import java.io.*;
import java.util.*;
class Main{
public static String output;
public static boolean match(String s1, String s2){
return s1.length() < s2.length() ? s1.equals(s2.substring(0,s1.length())) : s2.equals(s1.substring(0,s2.length()));
}
public static boolean matchall(Map m,String s){
Iterator iterator = m.entrySet().iterator();
while(iterator.hasNext()){
Map.Entry entry=(Map.Entry)iterator.next();
if(match((String)entry.getValue(), s))return true;
}
return false;
}
public static boolean dehuff(Map m,String s,String b,int cs,int cb){
if(cs>=s.length() || cb>=b.length()) return false;
char c=s.charAt(cs);
if(m.containsKey(c)){
String b0=(String)m.get(c);
int i0=b0.length();
if(cb+i0>b.length())return false;
if(b.substring(cb,cb+i0).equals(b0)){
if(cs==s.length()-1&&cb+i0==b.length()){
//set up output
Iterator iterator = (new TreeMap(m)).entrySet().iterator();
while(iterator.hasNext()){
Map.Entry entry=(Map.Entry)(iterator.next());
output+=String.format("%c = %s\n",entry.getKey(),entry.getValue());
}
return true;
}
return dehuff(m,s,b,cs+1,cb+i0);
}
return false;
}
int k=0;
for(int i=cb+1;i<=b.length();i++){
String x=b.substring(cb,i);
if(!matchall(m,x)){
m.put(c,x);
//System.out.println(c+" "+x);
if(cs==s.length()-1&&i==b.length()){
//set up output
Iterator iterator = (new TreeMap(m)).entrySet().iterator();
while(iterator.hasNext()){
Map.Entry entry=(Map.Entry)(iterator.next());
output+=String.format("%c = %s\n",entry.getKey(),entry.getValue());
}
return true;
}
if(dehuff(m,s,b,cs+1,i)){
//return true;
if(k==1)return false;k++;//計算量を急上昇させている元凶。
//PCは、S=s.length()-1、B=b.length()とすると、最悪(S+B)!/S!B!回計算しなければならない^^;
}
m.remove(c);
}
}
return k==1;
}
public static void main(String[] args){
Scanner cin=new Scanner(System.in);
int n=cin.nextInt();cin.nextLine();
for(int i=1;i<=n;i++){
output="";
System.out.println("DATASET #"+i);
String s=cin.nextLine(),b=cin.nextLine();
Map m=new HashMap();
if(!dehuff(m,s,b,0,0)){
System.out.println("MULTIPLE TABLES");
continue;
}
System.out.print(output);
}
}
}