poj 2475
上下文无关文法。经典。
代码:
#include<iostream>
#include<fstream>
using namespace std;
char c[300];
int map[201][201][4];
int Set(int ,int);
int ElemList (int,int);
int List(int,int);
int Elem(int,int);
int Atom(int,int);
int Atom(int s,int t){
if(s==t) return 1;
return 0;
}
int Elem(int s,int t){
if(map[s][t][3]>=0) return map[s][t][3];
map[s][t][3]=Atom(s,t)||Set(s,t);
return map[s][t][3];
}
int List(int s,int t){
if(map[s][t][2]>=0) return map[s][t][2];
if(Elem(s,t)){
map[s][t][2]=1;
return 1;
}
for(int i=s+1;i<t;i++)
if(c[i]==',')
{
if(Elem(s,i-1)&&List(i+1,t))
{
map[s][t][2]=1;
return 1;
}
}
map[s][t][2]=0;
return 0;
}
int ElemList(int s,int t){
if(map[s][t][1]>=0) return map[s][t][1];
if(s==t+1)
{
map[s][t][1]=1;
return 1;
}
map[s][t][1]=List(s,t);
return map[s][t][1];
}
int Set(int s,int t){
if(map[s][t][0]>=0) return map[s][t][0];
if(c[s]=='{'&&c[t]=='}')
map[s][t][0]=ElemList(s+1,t-1);
else map[s][t][0]=0;
return map[s][t][0];
}
void read(){
// ifstream cin("in.txt");
int i,j,k;
cin>>k;
for(i=1;i<=k;i++)
{
memset(map,-1,sizeof(map));
cin>>c;
Set(0,strlen(c)-1);
if(map[0][strlen(c)-1][0])
printf("Word #%d: Set\n",i);
else
printf("Word #%d: No Set\n",i);
}
}
int main(){
read();
return 0;
}
浙公网安备 33010602011771号