C ++程序查找水平和垂直线段之间的三角形数量

在本文中,我们将讨论一个程序,该程序查找通过合并给定水平线段和垂直线段的交点可以形成的三角形数量。

例如,假设我们已获得以下线段。在这里,我们有3个交点。因此,使用这些点可以形成的三角形数将为3 C 2

   |
---|--------|--
   |        |
   |  --|---|
   |        |

我们将遵循扫描线算法。我们将存储线段的所有值,然后检查其中一条线内的点是否也与任何其他线的内部点进行比较。这样,我们可以获取给定线段的所有交点,然后可以使用不同的可能组合轻松找到可能的三角形数量。

示例

#include<bits/stdc++.h>
#define maxy 1000005
#define maxn 10005
using namespace std;
//存储交点
struct i_point {
   int x, y;
   i_point(int a, int b) {
      x = a, y = b;
   }
};
int bit[maxy];
vector < pair <i_point, int> > events;
//给定点排序
bool com_points(pair<i_point, int> &a, pair<i_point, int> &b) {
   if ( a.first.x != b.first.x )
      return a.first.x < b.first.x;
   else {
      if (a.second == 3 && b.second == 3) {
         return true;
      }
      else if (a.second == 1 && b.second == 3) {
         return true;
      }
      else if (a.second == 3 && b.second == 1) {
         return false;
      }
      else if (a.second == 2 && b.second == 3) {
         return false;
      }
      return true;
   }
}
void topdate_line(int index, int value) {
   while (index < maxn) {
      bit[index] += value;
      index += index & (-index);
   }
}
int query(int index) {
   int res = 0;
   while (index > 0) {
      res += bit[index];
      index -= index & (-index);
   }
   return res;
}
//插入线段
void insertLine(i_point a, i_point b) {
   //如果是水平线
   if (a.y == b.y) {
      int begin = min(a.x, b.x);
      int end = max(a.x, b.x);
      events.push_back(make_pair(i_point(begin, a.y), 1));
      events.push_back(make_pair(i_point(end, a.y), 2));
   }
   //如果是垂直线
   else {
      int top = max(b.y, a.y);
      int bottom = min(b.y, a.y);
      events.push_back(make_pair(i_point(a.x, top), 3));
      events.push_back(make_pair(i_point(a.x, bottom), 3));
   }
}
//计算相交点的数量
int calc_i_points() {
   int i_points = 0;
   for (int i = 0 ; i < events.size() ; i++) {
      if (events[i].second == 1) {
         topdate_line(events[i].first.y, 1);
      }
      else if (events[i].second == 2) {
         topdate_line(events[i].first.y, -1);
      }
      else {
         int bottom = events[i++].first.y;
         int top = events[i].first.y;
         i_points += query(top) - query(bottom);
      }
   }
   return i_points;
}
int calc_triangles() {
   int points = calc_i_points();
   if ( points >= 3 )
      return ( points * (points - 1) * (points - 2) ) / 6;
   else
      return 0;
}
int main() {
   insertLine(i_point(3, 2), i_point(3, 13));
   insertLine(i_point(1, 5), i_point(3, 5));
   insertLine(i_point(8, 2), i_point(8, 8));
   insertLine(i_point(3, 4), i_point(6, 4));
   insertLine(i_point(4, 3), i_point(4, 5));
   sort(events.begin(), events.end(), com_points);
   cout << "Possible number of triangles : " << calc_triangles() << endl;
   return 0;
}

输出结果

Possible number of triangles : 1