#!/usr/bin/python3
# Encoding: utf8

# INPUT: non-zero matrix (filtered)
# ARGUMENT: a file of word pairs
# OUTPUT: each word pair is assigned a similarity value (dice)

import sys
import re
import math
from collections import defaultdict

file_name = sys.argv[1]
file = open(file_name, 'r')

##initializing dictionaries:
dic = defaultdict(dict) 
w = defaultdict(float)
simil = defaultdict(float)

def min(x,y):
    if x <= y:
        return float(x)
    else:
        return float(y)


for line in sys.stdin:  
    line = line.strip()  
    (word, context, weight) = line.split()
    #for word, context, weight in zip(*[iter(line)]*3):
 
    dic[word][context] = float(weight)
    w[word] += float(weight)
 

for line in file:
    line = line.strip() 
    (w1,w2) = line.split()
    common=0
    wc_count1=0
    wc_count2=0
    w1_count = w[w1]
    w2_count = w[w2]
    for context in dic[w1]:
        wc_count1 += dic[w1][context] **2
        #print (context, wc_count1, file=sys.stderr)
    for context in dic[w2]:
        wc_count2 += dic[w2][context] **2
        #print (context, wc_count2, file=sys.stderr)
        if context in dic[w1]:
            common += (dic[w1][context] * dic[w2][context])
            #print (context,w1,w2,dic[w1][context], dic[w2][context], common, wc_count1, wc_count2, file=sys.stderr)    
    simil[w1,w2] = (common) / math.sqrt (wc_count1 * wc_count2)
   #print ('%s\t%s\t%.6f' %  (w1, w2, simil[w1,w2]))
   #print (common, w1_count, w2_count)
       
    #print  >> sys.stderr, w1, w2, simil[w1,w2]
    print ('%s\t%s\t%.6f' %  (w1, w2, simil[w1,w2]))
