| ||||||||||
| Online Judge | Problem Set | Authors | Online Contests | User | ||||||
|---|---|---|---|---|---|---|---|---|---|---|
| Web Board Home Page F.A.Qs Statistical Charts | Current Contest Past Contests Scheduled Contests Award Contest | |||||||||
Re:为什么这题O(N*N)的算法还会超时,真的很不解!In Reply To:为什么O(N*N)的算法还会超时,真的很不解! Posted by:4404124 at 2007-06-02 12:28:28 以下是代码,请ACMER指点!
#include<iostream.h>
#include<string.h>
#include<math.h>
int p[101][101];
int t[101][101];
char str[101];
char q[101];
void back(int i,int j)//构造最优解
{while(1)
{if(i==j)
{if(str[i]=='(')
q[i]=')';
else if(str[i]==')')
q[i]='(';
else if(str[i]=='[')
q[i]=']';
else
q[i]='[';
return;
}
if(t[i][j]==0)
{i=i+1;
j=j-1;
}
else if(t[i][j]==1)
{ if(str[i]=='(')
q[i]=')';
else if(str[i]==')')
q[i]='(';
else if(str[i]=='[')
q[i]=']';
else
q[i]='[';
i=i+1;
}
else
{if(str[j]=='(')
q[j]=')';
else if(str[i]==')')
q[j]='(';
else if(str[i]=='[')
q[j]=']';
else
q[j]='[';
j=j-1;
}
}
}
void main()
{int i,j,m,k;
cin>>str;
m=strlen(str);
memset(p,0,sizeof(p));
memset(t,-2,sizeof(t));
for(i=0;i<101;i++)
q[i]='*';
for(i=0;i<m;i++)
p[i][i]=1;
for(k=1;k<m;k++)
for(i=0;i<m-k;i++)//求最优解
{j=i+k;
if(fabs(str[i]-str[j])==1||fabs(str[i]-str[j])==2)//如果str[i]与str[j]配对
{p[i][j]=p[i+1][j-1];
t[i][j]=0;
}
else
{if(p[i][j-1]>p[i+1][j])
{p[i][j]=p[i+1][j]+1;
t[i][j]=1;
}
else
{p[i][j]=p[i][j-1]+1;
t[i][j]=-1;
}
}
}
back(0,m-1);
for(i=0;i<m;i++)
if(q[i]=='*')
cout<<str[i];
else
{ if(q[i]==')'||q[i]==']')
cout<<str[i]<<q[i];
else
cout<<q[i]<<str[i];
}
cout<<endl;
}
Followed by: Post your reply here: |
All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator