標籤:
原題連結
http://acm.csu.edu.cn/OnlineJudge/problem.php?id=1809
DescriptionBobo has a balanced parenthesis sequence P=p1 p2…pn of length n and q questions.The i-th question is whether P remains balanced after pai and pbi swapped. Note that questions are individual so that they have no affect on others.Parenthesis sequence S is balanced if and only if:1. S is empty;2. or there exists
balanced parenthesis sequence A,B such that S=AB;3. or there exists
balanced parenthesis sequence S‘ such that S=(S‘).InputThe input contains at most 30 sets. For each set:The first line contains two integers n,q (2≤n≤105,1≤q≤105).The second line contains n characters p1 p2…pn.The i-th of the last q lines contains 2 integers ai,bi (1≤ai,bi≤n,ai≠bi).
OutputFor each question, output "
Yes" if P remains balanced, or "
No" otherwise.Sample Input
4 2(())1 32 32 1()1 2
Sample Output
NoYesNo
Source
湖南省第十二屆大學生電腦程式設計競賽
題意:給了一個平衡的括弧序列s(平衡是指括弧匹配正常) 現在q次詢問,每次輸入兩個數a、b 問將s[a] s[b]交換後是否任然平衡,平衡則輸出“Yes” 否則輸出“No”;
思路:定義數組num[] ,num[i]表示s[1]到s[i]中左括弧數減去右括弧數的差值,分析可知因為s是平衡括弧序列,那麼num[i]>=0 令a<b ,那麼交換s[a] s[b]後,只對num[a]~num[b-1]產生影響,並且交換後當num[k]<0(a<=k<b)時表示不平衡,而只有s[a]=‘(‘ s[b]=‘)‘ 交換後才可能使num[k]<0 。所以特判當s[a]=‘(‘ s[b]=‘)‘時,用線段樹求區間a~b-1的最小值,當最小值小於2時,即交換後不平衡,為什麼呢? s[a]=‘(‘ s[b]=‘)‘交換後num[a]~num[b-1]都減2;
代碼如下:
#include <iostream>#include <algorithm>#include <cstdio>#include <cstring>#include <cmath>#define eps 1e-8#define maxn 105#define inf 0x3f3f3f3f3f3f3f3f#define IN freopen("in.txt","r",stdin);using namespace std;char s[100005];int num[100005];int a,b; struct Node{ //int l,r; int v;}node[100005*4]; void build(int l,int r,int i){ if(l==r) { node[i].v=num[l]; return; } int mid=(l+r)>>1; build(l,mid,i<<1); build(mid+1,r,i<<1|1); node[i].v=min(node[i<<1].v,node[i<<1|1].v);} void query(int l,int r,int &tmp,int i){ if(l>=a&&r<=b) { tmp=node[i].v; return; } int mid=(l+r)>>1; if(mid>=b) query(l,mid,tmp,i<<1); else if(mid<a) query(mid+1,r,tmp,i<<1|1); else { int tmp2; query(l,mid,tmp,i<<1); query(mid+1,r,tmp2,i<<1|1); tmp=min(tmp,tmp2); }} int main(){ int n,q; while(scanf("%d%d",&n,&q)!=EOF) { scanf("%s",s+1); num[0]=0; for(int i=1;i<=n;i++) { num[i]=num[i-1]; if(s[i]==‘(‘) num[i]++; else num[i]--; } build(1,n,1); while(q--) { scanf("%d%d",&a,&b); if(a>b) swap(a,b); if(s[a]==s[b]||s[a]==‘)‘&&s[b]==‘(‘) puts("Yes"); else { b--; int tmp=99999999; query(1,n,tmp,1); if(tmp<2) puts("No"); else puts("Yes"); } } } return 0;}/**8 8(())(())2 7*/
2016年湖南省第十二屆大學生電腦程式設計競賽---Parenthesis(線段樹求區間最值)