题目链接:
https://www.nowcoder.com/acm/contest/140/J
思路:
都写在代码注释里了,非常好懂。。
for_each函数可以去看一下,遍历起vector数组比较方便,用for(int i = 0;i < q[i].size();i++)的话,是会有一些弊端的,虽然对于这道题应该没什么影响,但最好规范下。
耗时:2072ms
实现代码:
#include<bits/stdc++.h> using namespace std; const int M = 1e6+5; vector<int>t[M]; int n,m; vector<int>bit[M]; int lowbit(int x){return x&-x; }struct node{int a,b,c,d;node(){}node(int a1,int b1,int c1,int d1):a(a1),b(b1),c(c1),d(d1){} };struct node1{int i,j;node1(){}node1(int i1,int j1):i(i1),j(j1){} };vector<node1>k[M]; vector<node>q[M];void add(int x,int y,int z){for(int i=x;i<=n;i+=lowbit(i)){for(int j=y;j<=m;j+=lowbit(j))bit[i][j]+=z;} } void update(int x1,int y1,int x2,int y2,int z){add(x1,y1,z);add(x2+1,y2+1,z);add(x1,y2+1,-z);add(x2+1,y1,-z); } int sum(int x,int y){int res=0;for(int i=x;i;i-=lowbit(i)){for(int j=y;j;j-=lowbit(j)){res+=bit[i][j];}}return res; }template <class T> inline void scan_d(T &ret) {char c;ret = 0;while ((c = getchar()) < '0' || c > '9');while (c >= '0' && c <= '9'){ret = ret * 10 + (c - '0'), c = getchar();} }template <class T> inline void print_d(T x) {if (x > 9){print_d(x / 10);}putchar(x % 10 + '0'); }void fun1(node now){update(now.a,now.b,now.c,now.d,1); }void fun2(node now){update(now.a,now.b,now.c,now.d,-1); }int num; void fun3(node1 now){if(sum(now.i,now.j)) num++; }int main() {int t,x,a,b,c,d,z;scan_d(n); scan_d(m); scan_d(t);for(int i = 1;i <= n;i ++) bit[i].resize(m+1); //预开空间for(int i = 1;i <= n;i ++) {for(int j = 1;j <= m;j ++){scan_d(x);k[x].push_back(node1(i,j)); //需要x种类药的花的坐标 }}for(int i = 1;i <= t;i ++){scan_d(a);scan_d(b),scan_d(c),scan_d(d);scan_d(z);update(a,b,c,d,1); //标记代表这个区间被z种类药撒了q[z].push_back(node(a,b,c,d)); //存下z种类药一共撒了哪些区间 }num = 0;for(int i = 1;i <= n*m;i ++){ //遍历所有种类的药if(k[i].size()){ //存在需要ki种类药的花for_each(q[i].begin(),q[i].end(),fun2); //将ki种类药撒的区间造成的影响全部清0for_each(k[i].begin(),k[i].end(),fun3); //遍历需要k种类药的所有花的坐标如果这个坐标依旧为1,那么代表撒在它上面的并不是k种类的药,这朵花会死亡,num++;for_each(q[i].begin(),q[i].end(),fun1); //再将ki种类药撒的区间还原 }}print_d(num);printf("\n");return 0; }