单调栈真的是很可爱的东西!
应用也很多啊,应该多想想
#include<iostream>
#include<stdio.h>
#include<algorithm>
#include<string.h>
#include<vector>
#include<set>
#include<math.h>
#include<queue>
#include<map>
#include<stack>
#define go(i,a,b) for (int (i)=(a);(i)<=(b);(i)++)
#define ll long long
#define N 1000005
#define M 105
using namespace std;
typedef pair<int,int> pai;
vector<int>v[M];
int h[M];
bool cmp(int a, int b){
return a>b;
}
int main(){
int T,n,m,k,x,y,ca=0;
scanf("%d",&T);
while (T--){
scanf("%d%d%d",&n,&m,&k);
go(i,1,m) v[i].clear();
go(i,1,k){
scanf("%d%d",&x,&y);
v[y].push_back(x);
}
go(i,1,m) sort(v[i].begin(),v[i].end(),cmp);
memset(h,0,sizeof(h));
ll res=0,ans=0;
go(i,1,n){
stack<pai>s; //前面的是深度,然后是位置。
s.push(make_pair(0,0));
ans=0;
go(j,1,m){
if (!v[j].empty()&&v[j].back()==i){
v[j].pop_back();
h[j]=0;
while (!s.empty()) s.pop();
s.push(make_pair(0,j));
ans=0;
}
else{
h[j]++;
while(!s.empty()&&s.top().first>=h[j]){
pai tmp=s.top();
s.pop();
ans-=(tmp.second-s.top().second)*tmp.first;
}
ans+=(j-s.top().second)*h[j];
//cout<<ans<<endl;
res+=ans;
s.push(make_pair(h[j],j));
}
}
}
printf("Case #%d: %lld\n",++ca,res);
}
}