|
| 1 | +/* |
| 2 | + * Copyright (C) 2022, Saul Lawliet <october dot sunbathe at gmail dot com> |
| 3 | + * All rights reserved. |
| 4 | + * |
| 5 | + * 先计算所有的‘==’, 分好组 |
| 6 | + * 再计算所有的‘!=’, 如有同组的, 则 false |
| 7 | + * |
| 8 | + * 分组: 因为只要26个字母, 所以最多26个组, 然后对于每个等式, 把他们以递归的方式找到根部, 然后串起来 |
| 9 | + */ |
| 10 | + |
| 11 | +#include <stdbool.h> |
| 12 | +#include <stdint.h> |
| 13 | +#include "c/data-structures/array.h" |
| 14 | +#include "c/test.h" |
| 15 | + |
| 16 | +int find(int8_t data[], int x) { |
| 17 | + if (data[x] == x) return x; |
| 18 | + return find(data, data[x]); |
| 19 | +} |
| 20 | + |
| 21 | +bool equationsPossible(char **equations, int equationsSize) { |
| 22 | + int8_t data[26]; |
| 23 | + for (int i = 0; i < 26; i++) data[i] = i; |
| 24 | + |
| 25 | + for (int i = 0; i < equationsSize; i++) { |
| 26 | + if (equations[i][1] == '=') { |
| 27 | + data[find(data, equations[i][0] - 'a')] = find(data, equations[i][3] - 'a'); |
| 28 | + } |
| 29 | + } |
| 30 | + |
| 31 | + for (int i = 0; i < equationsSize; i++) { |
| 32 | + if (equations[i][1] != '=') { |
| 33 | + if (find(data, data[equations[i][0] - 'a']) == find(data, data[equations[i][3] - 'a'])) { |
| 34 | + return false; |
| 35 | + } |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + return true; |
| 40 | +} |
| 41 | + |
| 42 | +void test(bool expect, const char *equations) { |
| 43 | + arrayEntry *e = arrayParse1D(equations, ARRAY_STRING); |
| 44 | + EXPECT_EQ_INT(expect, equationsPossible(arrayValue(e), arraySize(e))); |
| 45 | + arrayFree(e); |
| 46 | +} |
| 47 | + |
| 48 | +int main(void) { |
| 49 | + test(false, "[a==b,b!=a]"); |
| 50 | + test(true, "[a==b,b==a]"); |
| 51 | + |
| 52 | + test(false, "[f==a,a==b,f!=e,a==c,b==e,c==f]"); |
| 53 | + |
| 54 | + return testOutput(); |
| 55 | +} |
0 commit comments