📜  碰撞课程| TCS MockVita 2020

📅  最后修改于: 2021-05-17 23:16:10             🧑  作者: Mango

问题描述

在繁忙的道路上,有多辆汽车经过。运行模拟,以查看如果道路上所有汽车的刹车均失败,会发生什么情况。确保他们安全的唯一方法是彼此之间不会发生碰撞和经过。目的是确定给定的任何汽车是否会在回旋处周围安全碰撞或经过。可以将其视为参考点O(坐标为(0,0)的原点),但是汽车绕过它而不是绕过它。

考虑到每辆汽车都以统一的速度朝原点直线移动。即使经过原点,汽车仍将继续沿相同的直线行驶。计算在这种情况下将发生的碰撞次数。

注意:仅在原点计算碰撞。忽略其他冲突。假设即使在碰撞后,每辆车仍沿其各自的路径行驶,并且在无限距离内不会改变方向或速度。

给定一个数组car [] ,其中包含每个元素的坐标及其速度。找到原点的碰撞总数。

例子:

方法:想法是找出在原点发生碰撞的汽车数量。给定汽车的坐标位置,从中可以找到汽车与原点的距离。

设x,y为汽车的位置,则距原点的距离为:

\sqrt{x^2 + y^2}

用速度除以该距离将为我们提供汽车在原点出现的时间。因此,如果在某个时刻的起点处有“ N”辆汽车出现,那么总碰撞次数将是

{n}\choose{2}

在不同的时间实例添加所有碰撞将提供我们所需的答案。

下面是上述方法的实现:

C++
// C++ implementation to find the
// collision at the origin
  
#include 
using namespace std;
  
// Structure to store the
// co-ordinates of car and speed
struct Car {
    long long x;
    long long y;
    long long v;
};
  
// Function to find the co-ordinates
// of the car and speed
long long solve(long long c,
                vector& arr)
{
    map freq;
  
    long sum = 0;
    for (long long i = 0; i < c; i++) {
        long long x = arr[i].x,
                  y = arr[i].y,
                  v = arr[i].v;
        long long dist_square
            = (x * x) + (y * y);
        long long time_square
            = dist_square / (v * v);
        freq[time_square]++;
    }
  
    // Loop to iterate over the
    // frequency of the elements
    for (auto it = freq.begin();
         it != freq.end(); it++) {
        long long f = it->second;
        if (f <= 0)
            continue;
  
        sum += (f * (f - 1)) / 2;
    }
  
    return sum;
}
  
// Driver Code
int main()
{
    long long c = 5;
  
    vector arr;
  
    Car tmp;
    tmp.x = 5;
    tmp.y = 12;
    tmp.v = 1;
    arr.push_back(tmp);
  
    tmp.x = 16;
    tmp.y = 63;
    tmp.v = 5;
    arr.push_back(tmp);
  
    tmp.x = -10;
    tmp.y = 24;
    tmp.v = 2;
    arr.push_back(tmp);
  
    tmp.x = 7;
    tmp.y = 24;
    tmp.v = 2;
    arr.push_back(tmp);
  
    tmp.x = -24;
    tmp.y = 7;
    tmp.v = 2;
    arr.push_back(tmp);
  
    cout << solve(c, arr);
  
    return 0;
}


输出:
4