题意:给出一个n * m的蛋糕,切 k 刀,每次从一个点(x,y)向 上下左右的一个方向切,问最后蛋糕被切成了几块
题解:显然,蛋糕的块数就是那么多线段的交点数 + 1。先离散,考虑向左切和向上切的,那么按照 y 的坐标递减排序,之后每一刀向上的切都是可以碰到之前向左切的线段的(如果之前的线段的x值比这刀向上的起点x大的话,图一话就很显然了)。之后向右切的和向上切的考虑的话,就是只要保证向右的起点x比向上的起点x小即可。同理讨论向右和向左分别和向下的情况。
贴一下丑陋的代码。。
#include<cstdio> #include<iostream> #include<algorithm> #include<cstring> #include<cmath> #include<stack> #include<cstdlib> #include<queue> #include<set> #include<string.h> #include<vector> #include<deque> #include<map> using namespace std; #define INF 0x3f3f3f3f #define eps 1e-4 #define bug printf("*********\n") #define debug(x) cout<<#x"=["<<x<<"]" <<endl typedef long long LL; typedef long long ll; const int MAXN = 2e5 + 5; const int maxn = 2e5 + 10; const int mod = 998244353; int c[MAXN]; struct line { int x, y, id, sx, sy;//sx sy 为离散后坐标 }s[maxn]; bool cmp1(line a,line b) { return a.sy > b.sy; } bool cmp2(line a,line b) { return a.sy < b.sy; } int lowbit(int x) { return x & (-x); } void update(int p) { while (p <= MAXN) { c[p] ++; p += lowbit(p); } } int getsum(int p) { int res = 0; while(p) { res += c[p]; p -= lowbit(p); } return res; } bool cmpx(const line& a, const line& b) { return a.x < b.x; } bool cmpy(const line& a, const line& b) { return a.y < b.y; } int arrx[maxn], arry[maxn]; int main() { int t; scanf("%d", &t); while (t--) { int n, m, k; char str[3]; scanf("%d %d %d", &n, &m, &k); char dir[5]; for (int i = 0; i < k; ++i) { scanf("%d %d %s", &s[i].x, &s[i].y, dir); arrx[i] = s[i].x; arry[i] = s[i].y; if (dir[0] == 'L') s[i].id = 1; else if (dir[0] == 'R') s[i].id = 2; else if (dir[0] == 'U') s[i].id = 3; else if (dir[0] == 'D') s[i].id = 4; } sort(s, s + k, cmpx); sort(arrx, arrx + k); n = unique(arrx, arrx + k) - arrx; int idx = 0; for (int i = 0; i < k; ++i) { if (s[i].x != arrx[idx]) ++idx; s[i].sx = idx + 1; } sort(s, s + k, cmpy); sort(arry, arry + k); m = unique(arry, arry + k) - arry; idx = 0; for (int i = 0; i < k; ++i) { if (s[i].y != arry[idx]) ++idx; s[i].sy = idx + 1; } sort(s, s + k, cmp1); LL sum = 1; memset(c, 0, sizeof c); for (int i = 0; i < k; i++) { if (s[i].id == 1) update(s[i].sx); if (s[i].id == 3) sum += (getsum(MAXN) - getsum(s[i].sx - 1)); } memset(c, 0, sizeof c); for (int i = 0; i < k; i++) { if (s[i].id == 2) update(s[i].sx); if (s[i].id == 3) sum += getsum(s[i].sx); } // cout << sum << endl; sort(s, s + k, cmp2); // for(int i = 0; i < k; i++) // printf("%d %d\n",s[i].sx,s[i].sy); memset(c, 0, sizeof c); for (int i = 0; i < k; i++) { if (s[i].id == 1) update(s[i].sx); if (s[i].id == 4) sum += getsum(MAXN) - getsum(s[i].sx - 1); } memset(c, 0, sizeof c); for (int i = 0; i < k; i++) { if (s[i].id == 2) update(s[i].sx); if (s[i].id == 4) sum += getsum(s[i].sx); } printf("%lld\n", sum); } }