If n = 1000, then according to 1 sec judgement time, algo with n^2 complexity should be run easily. But from past few times it shows TLE on my submissions.
Can someone suggest the problem in this thinking?
For eg.
Problem: https://leetcode.com/problems/min-cost-to-connect-all-points/
class Solution {
private:
vector<int> par, sz;
int get_par(int x) {
if (x != par[x])
par[x] = get_par(par[x]);
return par[x];
}
void join(int a, int b) {
a = get_par(a), b = get_par(b);
if (a != b) {
if (sz[a] < sz[b]) swap(a, b);
if (sz[a] == sz[b]) sz[a]++;
par[b] = a;
}
}
public:
int minCostConnectPoints(vector<vector<int>>& points) {
int n = points.size();
vector<vector<int>> dis;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
if (i != j) {
int res = abs(points[i][0] - points[j][0]) + abs(points[i][1] - points[j][1]);
vector<int> ext = {res, i, j};
dis.push_back(ext);
}
par = sz = vector<int>(n, 0);
for (int i = 0; i < n; i++)
par[i] = i;
sort(begin(dis), end(dis));
int ans = 0;
for (auto x : dis) {
int a = get_par(x[1]), b = get_par(x[2]);
if (a != b) {
join(x[1], x[2]);
ans += x[0];
}
}
return ans;
}
};As above code take n^2, but still it shows TLE in my browser.