您的位置:首页 > 其它

[JZOJ5029]. 【NOI2017模拟3.25】围墙

2017-03-29 22:14 411 查看

题目描述

蛐蛐国准备在和它的一个邻国——蝈蝈国之间修一堵围墙。

围墙可以看成是一个长度为n的括号序列,与此同时还有一个长度为n的排列P,一个围墙被称为稳的,当且仅当:

1、这个括号序列是合法的。

2、构造一张n个点的图,当且仅当第i个位置是左括号时,点i向右Pi连边,最后形成的图必须满足每个点度数均为一。保证对于任意i有Pi

一个括号序列合法的定义如下:

1、空序列是合法的。

2、如果“A”是合法的,那么“(A)”也是合法的。

3、如果“A”和“B”都是合法的,那么“AB”也是合法的。例如“()()((()()))”是合法的,而“())(()”不是。

现在蛐蛐国的领导人想知道一种合法的修墙方案。

本题由三个subtask,只有通过了一个subtask中的全部测试点才能获得该subtask中的所有分数。

subtask1:n=20,10分

subtask2:n=40,30分

subtask3:n=100,60分

分析

首先注意到这幅图每个点的度都为2,即是由多个环组成的。

奇环无解。

那么我们可以暴力枚举每个环的状态,要么环的第一条边选,然后第三条边选….依次下去,或者第二条边选,第四条边….

这样最差2n/2,过不了。

再考虑大小为2的环,肯定是标号小一点那个的出边选会更优嘛。

那么最差2n/4

做完了。

代码

#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
using namespace std;
typedef long long ll;
typedef double db;
#define fo(i,j,k) for(i=j;i<=k;i++)
#define fd(i,j,k) for(i=j;i>=k;i--)
const int N=205,mo=1000000007;
int a[N],bel[N],loop[N][N],tl[N],c[N],n,bt,pd[N],rec[N][N],prt
,ttt,pp,dp
,i,j,st;
void readin()
{
int i;
scanf("%d",&n);
fo(i,1,n)
scanf("%d",a+i);
}
void predo()
{
int i,x;
fo(i,1,n)
if (!pd[i])
{
tl[0]++;
x=i;
while (!pd[x])
{
pd[x]=1;
loop[tl[0]][++tl[tl[0]]]=x;
bel[x]=tl[0];
x=a[x];
}
c[++c[0]]=tl[0];
if (tl[tl[0]]==2)
{
dp[tl[0]]=1;
prt[min(loop[tl[0]][1],loop[tl[0]][2])]=1;
prt[max(loop[tl[0]][1],loop[tl[0]][2])]=-1;
}
}
}
void writ()
{
int i;
fo(i,1,n)
if (prt[i]==1)
printf("(");
else
if (prt[i]==-1)
printf(")");
else
printf(" ");
}
int check()
{
int tot=0,i,blk=0;
fo(i,1,n)
{
tot+=prt[i];
if (tot<0) return 0;
}
if (tot>0) return 0;
return 1;
}
int dfs(int x)
{
if (x>tl[0])
{
if (check())
{
writ();
pp=1;
}
return 0;
}
if (dp[x]) dfs(x+1);
else
{
int i,st=1;
fo(i,1,tl[x])
{
prt[loop[x][i]]=st;
st=-st;
}
dfs(x+1);
if (pp) return 0;
st=-1;
fo(i,1,tl[x])
{
prt[loop[x][i]]=st;
st=-st;
}
dfs(x+1);
}
}
int main()
{
freopen("wall.in","r",stdin);
freopen("wall.out","w",stdout);
readin();
predo();
fo(i,1,tl[bel
]) if (loop[bel
][i]==n)
{
dp[bel
]=1;
st=-1;
fo(j,i,tl[bel
]) prt[loop[bel
][j]]=st,st=-st;
st=1;
fd(j,i-1,1) prt[loop[bel
][j]]=st,st=-st;
}
dfs(1);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: