sunnyz's blog

By sunnyz, history, 20 months ago, In English

Connecting Two Barns

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();
    }
}

Full text and comments »

  • Vote: I like it
  • 0
  • Vote: I do not like it

By sunnyz, history, 20 months ago, In English

Hello friends! After 4 months of learning cp and 6 contests, I finally reach green! My next goal is to reach specialist in 1 month!

Don't give up, and always work toward your goal!

Full text and comments »

  • Vote: I like it
  • +18
  • Vote: I do not like it

By sunnyz, history, 21 month(s) ago, In English

Hi friends, I was recently bugged by this issue. I often find out that my coding ability doesn't support my thinking, and it often results in messy and chaotic code. For instance, on recent div3 D, I struggled to miss details. (I know the correct way to solve the problem) I've tried to practice more, but it often ends up with the same issue. So my question is, how do you improve your coding skill? (to the level where once you have an idea, you can instantly convert it to code)

Full text and comments »

  • Vote: I like it
  • 0
  • Vote: I do not like it