Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit f88bcf8

Browse files
Add 0990 satisfiability of equality equations
Signed-off-by: begeekmyfriend <begeekmyfriend@gmail.com>
1 parent 1270d7c commit f88bcf8

File tree

2 files changed

+76
-0
lines changed

2 files changed

+76
-0
lines changed
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
all:
2+
gcc -o test equality_equations.c
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
#include <assert.h>
2+
#include <stdbool.h>
3+
#include <stdio.h>
4+
#include <stdlib.h>
5+
6+
7+
struct ufs {
8+
int parents[512];
9+
};
10+
11+
static inline void ufs_init(struct ufs *set)
12+
{
13+
int i;
14+
for (i = 0; i < sizeof(set->parents) / sizeof(int); i++) {
15+
set->parents[i] = i;
16+
}
17+
}
18+
19+
static inline int ufs_find(struct ufs *set, int node)
20+
{
21+
assert(node >= 0 && node <= sizeof(set->parents) / sizeof(int));
22+
if (set->parents[node] != node) {
23+
set->parents[node] = ufs_find(set, set->parents[node]);
24+
}
25+
return set->parents[node];
26+
}
27+
28+
static inline void ufs_union(struct ufs *set, int p, int q)
29+
{
30+
int root_p, root_q;
31+
32+
root_p = ufs_find(set, p);
33+
root_q = ufs_find(set, q);
34+
/* Omit root_p == root_q if-condition */
35+
set->parents[root_p] = root_q;
36+
}
37+
38+
static inline bool ufs_connected(struct ufs *set, int p, int q)
39+
{
40+
return ufs_find(set, p) == ufs_find(set, q);
41+
}
42+
43+
bool equationsPossible(char ** equations, int equationsSize)
44+
{
45+
int i;
46+
struct ufs *set;
47+
48+
set = malloc(sizeof(*set));
49+
ufs_init(set);
50+
51+
for (i = 0; i < equationsSize; i++) {
52+
if (equations[i][1] == '=') {
53+
ufs_union(set, equations[i][0], equations[i][3]);
54+
}
55+
}
56+
57+
for (i = 0; i < equationsSize; i++) {
58+
if (equations[i][1] == '!') {
59+
if (ufs_connected(set, equations[i][0], equations[i][3])) {
60+
return false;
61+
}
62+
}
63+
}
64+
65+
return true;
66+
}
67+
68+
int main(int argc, char **argv)
69+
{
70+
//char *equations[] = {"a==b", "c==c", "x==y" };
71+
char *equations[] = {"a==b", "b!=c", "a==c" };
72+
printf("%s\n", equationsPossible(equations, sizeof(equations)/sizeof(char *)) ? "true" : "false");
73+
return 0;
74+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /