还是用到了离散化和二分查找的一个题目,题目是求每段线段可以达到最大的矩形面积,再求总和。
- /* Name: City Horizon
- Date: 31-07-08 17:06
- Description: 离散化+二分查找 用了个链表
- */
- #include<stdio.h>
- #include<stdlib.h>
- #include<algorithm>
- #define pr printf
- __int64 x[100003];
- int b[100003];
- struct stt{
- int s,e,h;
- }a[50003];
- int c[100003];
- int cmp(const void * a,const void * b){
- return (int)(*(__int64 *)a-*(__int64 *)b);
- }
- int cmp2(const void * b,const void *a){
- return ((stt *)a)->h-((stt *)b)->h;
- }
- //二分查找排序数组,返回匹配元素位置
- int search_bin(__int64 *t,__int64 k,int start,int end)
- { // t为待查数组,k为匹配元素,start数组起始位置,end数组结束位置
- int low=start,high=end-1,mid;
- while (low<=high)
- {
- mid=(low+high)/2;
- if (k==t[mid]) return mid;
- else if (k<t[mid]) high=mid-1;
- else low=mid+1;
- }
- return -1;
- }
- int main(){
- int i,n,s,e,h,k;
- scanf("%d",&n);
- FILE *pp=fopen("temp.txt","w");
- for(i=0,k=0;i<n;i++,k++)
- {
- scanf("%d%d%d",&a[i].s,&a[i].e,&a[i].h);
- x[k]=a[i].s,x[++k]=a[i].e;
- }
- for(i=0;i<2*n;i++)c[i]=0;
- qsort(x,2*n,sizeof(__int64),cmp);//将x坐标离散
- qsort(a,n,sizeof(a[1]),cmp2);//按高度排序
- __int64 sum=0,len;
- int x1,j,x2,next;
- for(i=0;i<2*n-1;i++)
- {
- b[i]=i+1;//初始化链表
- }
- for(i=0;i<n;i++)
- {
- s=a[i].s,e=a[i].e,h=a[i].h;
- x1=search_bin(x,s,0,2*n);
- x2=search_bin(x,e,0,2*n);
- len=0;
- for(j=x1;j<x2 && j<2*n;j=next)//链表是关键,保证了每个点只会便利一次
- {
- if(c[j]==0)//没有访问过的点
- {
- c[j]=1;
- len+=(x[j+1]-x[j]);
- next=b[j];
- b[j]=x2;
- }else next=b[j];//被覆盖的点根据链表找到下一点索引
- }
- sum+=len*h;
- }
- pr("%I64d/n",sum);
- scanf("%d",&i);
- }
- /*
- 4
- 1 15 1
- 3 7 4
- 3 12 5
- 5 8 3
- */