1 / 4
Mar 10
using namespace std;
void fast()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
}

//---------------------------------------------------------------------
//=====================================================================
//---------------------------------------------------------------------

bool bfs(vector<vector<int>> &g, int n, int city, int s, vector<int> &p)
{
    vector<int> depth(n + 1, 0);
    vector<int> vis(n + 1, 0);
    vis[city] = 1;
    queue<int> q;
    q.push(city);
    p[city]++;
    if (p[city] > 1)
        return true;
    while (q.size() != 0)
    {
        int f = q.front();
        q.pop();
        for (auto it : g[f])
        {
            if (vis[it])
                continue;
            if (depth[f] == s)
                return false;
            vis[it] = 1;
            depth[it] = depth[f] + 1;
            q.push(it);
            p[it]++;
            if (p[it] > 1)
                return true;
        }
    }
    return false;
}

void solve()
{
    int n, r, m;
    cin >> n >> r >> m;
    vector<vector<int>> g(n + 1);
    vector<int> p(n + 1, 0);
    for (int i = 0; i < r; i++)
    {
        int s, d;
        cin >> s >> d;
        if (s == d)
            continue;
        g[s].push_back(d);
        g[d].push_back(s);
    }
    vector<pair<int, int>> sol;
    for (int i = 1; i <= m; i++)
    {
        int city, s;
        cin >> city >> s;

        sol.push_back({city, s});
    }
    for (int i = 1; i <= m; i++)
    {

        if (bfs(g, n, sol[i - 1].first, sol[i - 1].second, p))
        {
            cout << "No\n";
            return;
        }
    }
    for (int i = 1; i <= n; i++)
    {
        if (p[i] != 1)
        {
            cout << "No\n";
            return;
        }
    }
    cout << "Yes\n";
    return;
}
int main()
{
    fast();
    int t = 1;
    cin >> t;
    while (t--)
        solve();
}

Why TLE is coming I am unable to understand.
If p[i] = protected[i] > 1 I am returning ans. So, in this approach TLE should not come.
Tell me where I am making mistake…

  • created

    Mar 10
  • last reply

    Mar 11
  • 3

    replies

  • 114

    views

  • 3

    users

I can’t see anything wrong with your code. My only suggestion is to replace the vectors with fixed size arrays for a small improvement. I don’t know whether that will be enough to get AC though.

I have tried your approach but it doesn’t work.
Multi Source BFS approach works.

Maybe you declare vectors to much time. Maybe declare once, use multitime. How?
something like:

vector <int> P;
P.reserve(as_much_as_you_want); //it's not necessery




samewhere in your code [in loop]:
P.resize(as_much_as_you_want);
////P.resize(0) <–> it is the same as P.delete()?