Only 3 testcases correct, rests are WA
I have being stuck on this problem for a long time, and I can't find out what's the bug. Can anyone please help me to find the bug?
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
#include <cmath>
using namespace std;
void find(int node, vector<int>& g, vector<int>* adj, bool* vis){
g.push_back(node);
vis[node]=1;
for(auto u : adj[node]){
if(!vis[u]){
find(u, g, adj, vis);
}
}
}
void solve(){
int n, m; cin>>n>>m;
vector<int> adj[n+5];
bool vis[n+5];
memset(vis, 0, sizeof(vis));
for(int i=0;i<m;i++){
int a,b; cin>>a>>b;
adj[a].push_back(b);
adj[b].push_back(a);
}
vector<int> F, G;
find(1, F, adj, vis), find(n, G, adj, vis);
sort(F.begin(), F.end());
sort(G.begin(), G.end());
long long cost=1e11;
for(int i=1;i<=n;i++){
//with the connected component of 1
bool c=1;
long long costOne, costN;
if(c){
long long c1=1e11, c2=1e11, closestIdx=upper_bound(F.begin(), F.end(), i)-F.begin();
if(closestIdx<F.size()) c2=pow(abs(i-F[closestIdx]), 2);
if(closestIdx-1>=0) c1=pow(abs(i-F[closestIdx-1]), 2);
costOne=min(c1, c2);
}
//with the connected component of n
if(c){
long long c1=1e11, c2=1e11, closestIdx=upper_bound(G.begin(), G.end(), i)-G.begin();
if(closestIdx<G.size()) c2=pow(abs(i-G[closestIdx]), 2);
if(closestIdx-1>=0) c1=pow(abs(i-G[closestIdx-1]), 2);
costN=min(c1, c2);
}
cost=min(cost, costOne+costN);
}
cout<<cost<<endl;
}
int main(){
int t; cin>>t;
while(t--){
solve();
}
}