Type the Question

Thursday, February 21, 2019

Question Name: Missing Soldiers

#include <bits/stdc++.h>
using namespace std;
#define LL long long int
vector<pair<int, int>> ev;
bool compare(pair<int, int> a, pair<int, int> b) {
    if (a.first != b.first) return a.first < b.first;
    return a.second < b.second;
}
int main() {
    int n, i;
    cin >> n;
    for (i=0;i<n;i++) {
        int x, y, d;
        cin >> x >> y >> d;
        ev.push_back({x, x+d});
    }
    sort(ev.begin(), ev.end(), compare);
    LL op = 0, cl = -1, ans = 0;
    for (auto it : ev) {
        if (cl < it.first) {
            ans += cl - op + 1;
            op = it.first;
            cl = it.second;
        } else cl = max(cl, it.second * 1LL);
    }
    ans += cl - op + 1;
    cout << ans << '\n';
    return 0;
}
  • Problem Description
    An infinite army of ants is marching on an infinite 2-D plane. Since ants are disciplined, here’s how they march: each ant chooses exactly one x coordinate and moves along it in positive y direction, starting from (x, 0). There exists exactly one ant for each x coordinate on that plane and hence there are infinite ants!

    There are N horizontal barriers lying on this plane. The ith barrier is defined by (xi, yi) and di, which means that the barrier is blocking all ants which want to pass through points lying on line segment connecting (xi, yi) and (xi + di, yi). Once an ant encounters a barrier, it stops moving.

    Given all the barriers, your task is to find the total number of ants, that will be ever blocked at some point in their march.

    INPUT

    The first line contains an integer N which denotes the number of barriers. Next N lines follow, each contains 3 space separated integers, “xi yi di” as explained in problem statement above.

    Note: The barriers in the input may overlap.

    OUTPUT

    Output a single integer, the number of ants that will be ever blocked at some point in their march.

    CONSTRAINTS

    1<= N <= 10^5
    1 <= xi, yi, di <= 10^9
  • Test Case 1
    Input (stdin)2
    1 1 4
    7 3 5
    Expected Output11
  • Test Case 2
    Input (stdin)6
    6 9 5
    8 10 8
    3 6 4
    8 3 6
    3 3 8
    4 2 4
    Expected Output14

No comments:

Post a Comment

Question Name:TOWER OF HANOI

#include < bits / stdc ++. h > #define lli long long using namespace std ; lli dp [ 202 ]; int main () { int t , n ; ...