生活随笔
收集整理的這篇文章主要介紹了
HDU - 5820 Lights(主席树)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目鏈接:點擊查看
題目大意:給出一個 n * m 的矩陣,再給出 N 個點,問其中的任意兩個點 ( x1 , y1 ) 與 ( x2 , y2 ) 之間,最短路徑為 abs( x1 - x2 ) + abs( y1 - y2 ) ,是否存在一條最短路徑,使得拐彎的地方都存在著點
題目分析:正難則反,我們可以選定一個矩形區域作為非法區域,若非法區域內存在點的話,那么答案顯然就是 NO 了
這樣的話必須要正著掃一遍,再倒著掃一遍,不然沒法同時解決以下兩個樣例:
?
input:
2
1 3
3 1
2
1 1
3 3
output:
NO
NO
代碼:
?
#include<iostream>
#include<cstdio>
#include<string>
#include<ctime>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<stack>
#include<climits>
#include<queue>
#include<map>
#include<set>
#include<sstream>
#include<cassert>
using namespace std;typedef long long LL;typedef unsigned long long ull;const int inf=0x3f3f3f3f;const int N=5e5+100;const int M=5e4+100;int prex[M],prey[M],n;pair<int,int>p[N];
/*主席樹*/
struct Node
{int l,r,sum;
}tree[N*30];int root[N],cnt;void init()
{memset(prex,0,sizeof(prex));memset(prey,0,sizeof(prey));root[0]=0;tree[0].l=tree[0].r=tree[0].sum=0;cnt=1;
}void change(int pos,int &k,int l,int r)
{tree[cnt++]=tree[k];k=cnt-1;tree[k].sum++;if(l==r)return;int mid=l+r>>1;if(pos<=mid)change(pos,tree[k].l,l,mid);elsechange(pos,tree[k].r,mid+1,r);
}int query(int i,int j,int l,int r,int L,int R)//左根,右根,當前區間,目標區間
{if(L>R)return 0;if(l>=L&&r<=R)return tree[j].sum-tree[i].sum;if(r<L||l>R)return 0;int mid=l+r>>1;return query(tree[i].l,tree[j].l,l,mid,L,R)+query(tree[i].r,tree[j].r,mid+1,r,L,R);
}
/*主席樹*/
bool solve()
{init();int last=0;for(int i=1;i<=n;i++){if(p[i].first==p[i-1].first&&p[i].second==p[i-1].second)continue;int x=p[i].first,y=p[i].second;int xx=p[prey[y]].first,yy=p[prex[x]].second;root[x]=root[last];change(y,root[x],1,M);if(query(root[xx],root[x],1,M,yy+1,y-1))return false;last=x,prex[x]=i,prey[y]=i;}return true;
}int main()
{
#ifndef ONLINE_JUDGE
// freopen("input.txt","r",stdin);
// freopen("output.txt","w",stdout);
#endif
// ios::sync_with_stdio(false);while(scanf("%d",&n)!=EOF&&n){for(int i=1;i<=n;i++)scanf("%d%d",&p[i].first,&p[i].second);sort(p+1,p+1+n);bool flag=solve();for(int i=1;i<=n;i++)p[i].first=M-p[i].first;sort(p+1,p+1+n);flag&=solve();if(flag)puts("YES");elseputs("NO");}return 0;
}
?
總結
以上是生活随笔為你收集整理的HDU - 5820 Lights(主席树)的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。