I am getting wrong answer over 7th testcase I am not able to figure out kindly help me … my link is below.
else if (s == "get")
{
int u;
cin >> u;
cout << exp1[u] << "\n";
}
The following changes should work.
else if (s == "get")
{
int u;
cin >> u;
cout << exp1[find_set(u)] << "\n";
}
Not working
It’s a common mistake to always remember the parent doesn’t get updated to all the nodes unless you run the find_set function, so try to use it whenever required.
Ignore my previous post. It was a blunder.
Try this.
Your Code, modified
#include<bits/stdc++.h>
using namespace std;
std::vector<int> rank1(300005);
std::vector<int> parent(300005);
std::vector<int> exp1(300005, 0);
int find_set(int v)
{
return v == parent[v] ? v : parent[v] = find_set(parent[v]);
}
void make_Set(int v)
{
parent[v] = v;
rank1[v] = 0;
exp1[v] = 0;
}
void union_sets(int u, int v)
{
int a = find_set(u);
int b = find_set(v);
if (a != b)
{
if (rank1[a] < rank1[b])
{
swap(a, b);
}
parent[b] = a;
if (rank1[a] == rank1[b])
rank1[a]++;
}
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("input_cf_edu.txt", "r", stdin);
freopen("output_cf_edu.txt", "w", stdout);
#endif
ios_base::sync_with_stdio(false);
cin.tie(0);
int n, m;
cin >> n >> m;
//cout << "hi";
for (int i = 1; i <= n; i++)
{
make_Set(i);
}
while (m--)
{
string s;
cin >> s;
//cout << s << endl;
if (s == "join")
{
int u, v;
cin >> u >> v;
union_sets(u, v);
}
else if (s == "get")
{
int u;
cin >> u;
cout << exp1[u] << "\n";
}
else if (s == "add")
{
int x, v;
cin >> x >> v;
int m = find_set(x);
for (int i = 1; i <= n; i++)
{
if (find_set(i) == m) // the change is here
{
exp1[i] = exp1[i] + v;
}
}
}
}
return 0;
}
Anyways, I tried submitting. It’s TLE on Test Case 22 Now.