|
| 1 | +```java |
| 2 | + |
| 3 | +import java.util.*; |
| 4 | +import java.io.*; |
| 5 | + |
| 6 | +class SegTree{ |
| 7 | + int[] tree; |
| 8 | + SegTree(int size){ |
| 9 | + tree = new int[size*4+1]; |
| 10 | + } |
| 11 | + |
| 12 | + void upt(int s, int e, int i, int n) { |
| 13 | + if(s==e) { |
| 14 | + tree[n] = 1; |
| 15 | + return; |
| 16 | + } |
| 17 | + int m=(s+e)>>1; |
| 18 | + if(i<=m) upt(s,m,i,n*2); |
| 19 | + else upt(m+1,e,i,n*2+1); |
| 20 | + tree[n] = tree[n*2] + tree[n*2+1]; |
| 21 | + } |
| 22 | + |
| 23 | + int find(int s, int e, int l, int r, int n) { |
| 24 | + if(l>r || l>e || r<s) return 0; |
| 25 | + if(l<=s && e<=r) return tree[n]; |
| 26 | + int m=(s+e)>>1; |
| 27 | + return find(s,m,l,r,n*2) + find(m+1,e,l,r,n*2+1); |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +class Main { |
| 32 | + |
| 33 | + // IO field |
| 34 | + static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 35 | + static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); |
| 36 | + static StringTokenizer st = new StringTokenizer(""); |
| 37 | + |
| 38 | + static void nextLine() throws Exception {st = new StringTokenizer(br.readLine());} |
| 39 | + static String nextToken() throws Exception { |
| 40 | + if(!st.hasMoreTokens()) nextLine(); |
| 41 | + return st.nextToken(); |
| 42 | + } |
| 43 | + static int nextInt() throws Exception { return Integer.parseInt(nextToken()); } |
| 44 | + static long nextLong() throws Exception { return Long.parseLong(nextToken()); } |
| 45 | + static void bwEnd() throws Exception {bw.flush();bw.close();} |
| 46 | + |
| 47 | + // Additional field |
| 48 | + |
| 49 | + static int N; |
| 50 | + static SegTree seg; |
| 51 | + static TreeMap<String, Integer> T; |
| 52 | + |
| 53 | + public static void main(String[] args) throws Exception { |
| 54 | + |
| 55 | + for(N = nextInt();N != 0;N = nextInt()) { |
| 56 | + |
| 57 | + ready(); |
| 58 | + solve(); |
| 59 | + } |
| 60 | + |
| 61 | + bwEnd(); |
| 62 | + |
| 63 | + } |
| 64 | + |
| 65 | + static void ready() throws Exception{ |
| 66 | + |
| 67 | + T = new TreeMap<>(); |
| 68 | + seg = new SegTree(N); |
| 69 | + for(int i=1;i<=N;i++) T.put(nextToken(), i); |
| 70 | + |
| 71 | + } |
| 72 | + |
| 73 | + static void solve() throws Exception{ |
| 74 | + |
| 75 | + long ans = 0; |
| 76 | + for(int i=1;i<=N;i++) { |
| 77 | + int x = T.get(nextToken()); |
| 78 | + ans += seg.find(1, N, x, N, 1); |
| 79 | + seg.upt(1,N,x,1); |
| 80 | + } |
| 81 | + bw.write(ans + "\n"); |
| 82 | + |
| 83 | + } |
| 84 | + |
| 85 | +} |
| 86 | + |
| 87 | +``` |
0 commit comments