ACM模板库

ACM模板库


单调栈求全1矩阵数量

<pre><code class="language-cpp">#include &lt;iostream&gt; #include &lt;vector&gt; using namespace std; typedef long long ll; const int maxn = 5005; vector&lt;int&gt; v; int mp[maxn][maxn]; ll cnt[maxn][maxn]; int n, m; ll ans = 0; int main(){ scanf("%d%d", &amp;n, &amp;m); for(int i = 1; i &lt;= n; i++){ for(int j = 1; j &lt;= n; j++){ mp[i][j] = 1; } } for(int i = 1; i &lt;= m; i++){ int a, b; scanf("%d%d", &amp;a, &amp;b); mp[a][b] = 0; } for(int i = 1; i &lt;= n; i++){ for(int j = 1; j &lt;= n; j++){ if(mp[j][i] != 0) mp[j][i] = mp[j-1][i] + 1; } } for(int i = 1; i &lt;= n; i++){ v.clear(); for(int j = 1; j &lt;= n; j++){ while(v.size() &amp;&amp; mp[i][v.back()] &gt; mp[i][j]) v.pop_back(); v.push_back(j); if(v.size() &gt; 1){ cnt[i][j] += cnt[i][v[v.size()-2]]; cnt[i][j] += 1ll * (j - v[v.size()-2]) * mp[i][j]; }else{ cnt[i][j] += 1ll * j * mp[i][j]; } ans += cnt[i][j]; } } printf("%lld", ans); }</code></pre>

页面列表

ITEM_HTML