zoukankan      html  css  js  c++  java
  • 【洛谷P1823】音乐会的等待 单调栈+二分

    题目大意:给定一个长度为 N 的序列,定义两个数 (a[i],a[j]) 相互看得见,意味着 (forall kin [i+1,j-1],a[k]le a[i],a[k]le a[j]),求序列中共有多少对数可以看得见。

    题解:将序列得每一个值面向左边排序,从左到右扫每一个数,为了避免重复计数,每一个数作为最右边的数进行统计答案贡献,即:在单调栈中二分大于当前值得最小值,算入答案贡献即可。

    代码如下

    #include <bits/stdc++.h>
    using namespace std;
    const int maxn=5e5+10;
    const int inf=0x7fffffff;
    
    inline int read(){
    	int x=0,f=1;char ch;
    	do{ch=getchar();if(ch=='-')f=-1;}while(!isdigit(ch));
    	do{x=x*10+ch-'0';ch=getchar();}while(isdigit(ch));
    	return f*x;
    }
    
    int n,h[maxn],stk[maxn],top;
    long long ans;
    
    void read_and_parse(){
    	n=read();
    	for(int i=1;i<=n;i++)h[i]=read();
    }
    
    void calc(int x){
    	int l=0,r=top;
    	while(l<r){
    		int mid=l+r+1>>1;
    		if(h[stk[mid]]>x)l=mid;
    		else r=mid-1;
    	}
    	if(!l)ans+=top;
    	else ans+=top-l+1;
    }
    
    void solve(){
    	h[0]=inf;
    	for(int i=1;i<=n;i++){
    		calc(h[i]);
    		while(top&&h[i]>h[stk[top]])top--;
    		stk[++top]=i;
    	}
    	printf("%lld
    ",ans);
    }
     
    int main(){
    	read_and_parse();
    	solve();
    	return 0;
    }
    
  • 相关阅读:
    为什么硬链接不能链接目录、文件inode 和目录 dentry 的区别联系
    LVM 详解
    pwd 命令详解
    type 命令详解
    查看文件中字符出现次数
    lesson
    xml linq
    新系统配置
    空合并运算符(??):
    dos.ORM配置和使用
  • 原文地址:https://www.cnblogs.com/wzj-xhjbk/p/10071711.html
Copyright © 2011-2022 走看看