HDU 6299 Balanced Sequence

题目

题目的意思是给你很多个字符串包含‘(’和‘)’,你可以改变这些字符串的顺序但是不能改变字符串本身。问你最多能有多少括号匹配,一个左括号在一个右括号的左边他们就可以匹配。输出匹配书乘2。

比赛的时候总觉得自己可以想出来,但是就是怎么排序完全没有思路。

看了题解发现自己还有一些理解没有到位,比如说这里的是子序列,所以中间的连接不会有浪费的,不必考虑。

题解直接排序,虽然看了题解写了一个排序函数AC了,但是实际上我对这个排序函数还是不很理解。

总结来说:

(1)假设贡献k=左括号数-右括号数,那么sgn(k)>0的字符串一定在sgn(k)<=0的左边(这里其实有一个细节WA了一发)

(2)同时sgn(k)>0的字符串,按照右括号数从小到大排序

(3)同时sgn(k)<0的字符串,按照左括号数从大到小排序

 

代码

#include<iostream>
#include<stdio.h> 
#include<algorithm>
#include<string.h>
#include<vector>
#include<set>
#include<math.h>
#include<queue>
#include<map>
#include<stack>
#define go(i,a,b) for (ll (i)=(a);(i)<=(b);(i)++)
#define ll long long
#define N 100005
using namespace std;

char s[100005];

struct str{
	ll l,r;  //(:左括号  ):右括号 
}a[N];
ll ans;
//这里要的是序列,所以只用匹配就可以了
int sgn(int x){
	return x==0?0:(x>0?1:-1);
}
bool cmp1(str a, str b){
	int tmp1=a.l-a.r;
	int tmp2=b.l-b.r;
	if (sgn(tmp1)==sgn(tmp2)){
		if (sgn(tmp1)<=0) return a.l>b.l; //(少,)多,应该按照(从多到少 
		else return a.r<b.r; // (多,)少,应该按照)从少到多,尽量减少浪费)浪费 
	}
	else return sgn(tmp1)>sgn(tmp2);
}
int main(){
	ll T,n,len,cntl,cntr;
	scanf("%lld",&T);
	while(T--){
		scanf("%lld",&n); ans=0;
		go(i,1,n){
			scanf("%s",s); len=strlen(s);
			cntl=0; cntr=0;
			go(j,0,len-1){
				if (s[j]=='('){
					cntl++;
				}
				else {
					if (cntl>0){
						ans+=2;
						cntl--;
					}
					else cntr++;
				}
			}
			a[i].l=cntl;
			a[i].r=cntr;
		}
		sort(a+1,a+1+n,cmp1);
		cntl=0;
		go(i,1,n){
			ans+=(min(cntl,a[i].r)*2);
			cntl-=min(cntl,a[i].r);
			cntl+=a[i].l;
			//cout<<suml<<endl;
		}
		printf("%lld\n",ans);
	}
	return 0;
}

排序

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值