-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathFriendCircleQueries.cs
109 lines (87 loc) · 2.84 KB
/
FriendCircleQueries.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
// Friend Circle Queries
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text.RegularExpressions;
using System.Text;
using System;
class Solution {
// Complete the maxCircle function below.
static int[] maxCircle(int[][] queries)
{
var ds = new DisjointSets();
var result = new int[queries.Length];
var max = 0;
for (int index = 0; index < queries.Length; index++)
{
var left = ds.FindOrAdd(queries[index][0]);
var right = ds.FindOrAdd(queries[index][1]);
max = Math.Max(max, ds.Union(left, right));
result[index] = max;
}
return result;
}
class DisjointSets
{
Dictionary<int, int> Parents = new Dictionary<int, int>();
Dictionary<int, int> Counts = new Dictionary<int, int>();
Dictionary<int, int> Level = new Dictionary<int, int>();
public void AddNew(int key)
{
Parents.Add(key, key);
Counts.Add(key, 1);
Level.Add(key, 1);
}
public int Find(int value) => Parents[value] == value ? value : Find(Parents[value]);
public int FindOrAdd(int value)
{
if(Parents.ContainsKey(value))
return Find(value);
AddNew(value);
return value;
}
public int Union(int left, int right)
{
if(left == right) return Counts[left];
int newLevel;
if (Level[left] > Level[right])
{
newLevel = Level[left];
}
else if (Level[left] < Level[right])
{
newLevel = Level[right];
var temp = left;
left = right;
right = temp;
}
else
{
newLevel = Level[left] + 1;
}
Parents[right] = left;
Counts[left] = Counts[left] + Counts[right];
Level[left] = newLevel;
return Counts[left];
}
}
static void Main(string[] args) {
TextWriter textWriter = new StreamWriter(@System.Environment.GetEnvironmentVariable("OUTPUT_PATH"), true);
int q = Convert.ToInt32(Console.ReadLine());
int[][] queries = new int[q][];
for (int i = 0; i < q; i++) {
queries[i] = Array.ConvertAll(Console.ReadLine().Split(' '), queriesTemp => Convert.ToInt32(queriesTemp));
}
int[] ans = maxCircle(queries);
textWriter.WriteLine(string.Join("\n", ans));
textWriter.Flush();
textWriter.Close();
}
}