因為輸入的 value 不為負值且兩項量的任意 dim 最多都只會出現一次,而只有在都出現時該 dim 才會是需要計算成內積的,所以用負負得正的觀念,第一次存入 value 時存-value,第二次又出現(兩個向量都有)時再 *-value,就會變成正值,最後在輸出時沒出現過的會是 0,只出現過一次的會是負值,出現過兩次的才是正值。就可以過濾出兩項量都出現的情況,最後將過濾出的值相加即可。
完整程式碼
AC (6ms, 608KB)
#include<stdio.h> #include<stdlib.h>
typedefstructHash { unsignedint Key; int Value; structHash* Next; }Hash;
Hash HashTable[1024];
inlinevoidAddHash(int key, int value) { Hash* now = &HashTable[key & 1023]; while (now->Key != key) { if (now->Next == NULL) { now = now->Next = malloc(sizeof(Hash)); now->Key = key; now->Next = NULL; now->Value = -value; return; } now = now->Next; } now->Value *= -value; }
intgetInner() { int res = 0; Hash* now, * tmp; for (int i = 0; i < 1024; i++) { if (HashTable[i].Next != NULL) { now = HashTable[i].Next; do { if (now->Value > 0) res += now->Value; tmp = now; now = now->Next; free(tmp); } while (now != NULL); HashTable[i].Next = NULL; } } return res; }
intmain() { int n, m, v = 1; while (scanf(" %d:%d", &n, &m) == 2) { if (n + m) AddHash(n, m); elseif (v) v = 0; else printf("%d\n", getInner()), v = 1; } return0; }