题意:有两张对集合的操作:
1、G1 J G2 所有的(i,j)连一条线,i∈G1 , j∈G2,G1和G2合并为一个集合。
2、G1 U G2 将G1和G2合并为一个集合。
现在要给一个集合的每个数标号,最小从1开始,要求如果有两个点标号一样,那么这两个点的路径上一定要存在至少一个点,使得它的序号大于这两个点的序号。
给出一个合并顺序,求最后得到的集合标号后最大标号的最小值。
思路:
这里用f(A)表示A集合的最大标号最小值。num(A)表示A集合含的元素个数。
设两个集合A,B。
①最初的集合,A只含一个点,那么f(A) = 1。
②A U B,合并后的最小值为两个集合中最小值取最大,因为没有连边,所以最小值不变。f(A U B) = max( f(A) , f(B) )
③A J B,A集合中的每个数都要去连B集合中的每个数,那么A中的标号一定不可以和B中的任意相同,否则会出现相同标号直连的情况。那么A就得从f(B)+1开始标号。
而且A中的标号不可以相同,因为B中的每个元素都和A中的所有相连,如果A中有相同的,会出现x - y - x(x>y.
所以f(A U B) = min( f(A) + num(B) , f(B) + num(A) ).
#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <stack>
#include <map>
#include <set>
#include <vector>
#include <sstream>
#include <queue>
#include <utility>
using namespace std;
#define rep(i,j,k) for (int i=j;i<=k;i++)
#define Rrep(i,j,k) for (int i=j;i>=k;i--)
#define Clean(x,y) memset(x,y,sizeof(x))
#define LL long long
#define ULL unsigned long long
#define inf 0x7fffffff
#define mod 100000007
const int maxn = 100009;
int T;
int n;
int tot = 0;
char s[maxn];
int pos[10009];
struct node
{
int rk;
int num;
node( int tx = 0 , int ty = 0 ):rk(tx),num(ty){}
};
node U( node x , node y )
{
node ans;
ans.num = x.num + y.num;
ans.rk = max( x.rk , y.rk );
return ans;
}
node J( node x , node y )
{
node ans;
ans.num = x.num + y.num;
ans.rk = min( x.rk + y.num , x.num + y.rk );
return ans;
}
node dfs( int l , int r )
{
int x = 0;
int y = 0;
rep(i,l,r)
if ( s[i] == '(' ) x++;
else if ( s[i] == ')' ) y++;
else if ( s[i] == 'U' && x == y )
return U( dfs( l + 1 , i - 2 ) , dfs( i + 2 , r - 1 ) );
else if ( s[i] == 'J' && x == y )
return J( dfs( l + 1 , i - 2 ) , dfs( i + 2 , r - 1 ) );
return node( 1 , 1 );
}
int main()
{
cin>>T;
while(T--)
{
scanf("%d\n",&n);
gets(s);
node ans = dfs( 0 , strlen(s) - 1 );
printf("%d\n",ans.rk);
}
return 0;
}