uva 442 - Matrix Chain Multiplication

表示从今以后要好好学习,代码写的太烂了

题目大意是求最少的计算次数,唉。。。

最大收获是学会了求表达式中各部分的优先级

  
    
#include < stdio.h >
#include
< stdlib.h >
typedef
struct _matrix
{
char c;
int row;
int col;
int rank;
struct _matrix * next;
struct _matrix * last;
}matrix;
matrix symbol[
30 ];
char s[ 200 ];
char * _s;
int i,n,rank,first,error,sum,max;
matrix
* head, * now, * p, * _p, * pp, * end;
void getsum()
{
error
= 0 ;
for (i = max;i >= 0 && head -> next != NULL;i -- )
{
p
= head;
while (p -> rank != i && p != NULL)
p
= p -> next;
if (p -> next == NULL || p -> rank != p -> next -> rank)
{
p
-> rank -- ;
continue ;
}

while (p -> next != NULL && p -> rank == p -> next -> rank)
{
if (p -> col != p -> next -> row)
{
error
= 1 ;
break ;
}
sum
+= (p -> row) * (p -> col) * (p -> next -> col);


now
= (matrix * )malloc( sizeof (matrix));
now
-> row = p -> row;
now
-> col = p -> next -> col;
now
-> rank = p -> rank;

_p
= p -> last;
pp
= p -> next -> next;
if (head -> next -> next == NULL)
{
free(p
-> next);
free(p);
head
= now;
head
-> next = NULL;
p
= head;
break ;
}
else if (p == head)
{
head
= now;
now
-> next = pp;
pp
-> last = now;
head
-> last = NULL;
}
else if (p -> next == end)
{
end
= now;
end
-> next = NULL;
_p
-> next = now;
now
-> last = _p;
}
else
{
_p
-> next = now;
now
-> next = pp;
pp
-> last = now;
now
-> last = _p;
}
free(p
-> next);
free(p);
p
= now;
}
now
-> rank -- ;
if (error)
break ;
}
}
int main()
{
scanf(
" %d " , & n);
for (i = 0 ;i < n;i ++ )
{
getchar();
scanf(
" %c%d%d " , & symbol[i].c, & symbol[i].row, & symbol[i].col);
}
getchar();
while (gets(s))
{
_s
= s;
rank
= 0 ;
first
= 1 ;
max
= 0 ;
sum
= 0 ;
while ( * _s)
{
if ( * _s == ' ( ' )
{
rank
++ ;
if (rank > max)
max
= rank;
}
else if ( * _s == ' ) ' )
{
rank
-- ;
if ( * (_s + 1 ) == ' ( ' )
{
getsum();
if (error)
break ;
head
-> rank = 0 ;
rank
= 0 ;
max
= 0 ;
first
= 2 ;
}
}
else
{
now
= (matrix * )malloc( sizeof (matrix));
for (i = 0 ; * _s != symbol[i].c;i ++ );
now
-> c =* _s;
now
-> rank = rank;
now
-> row = symbol[i].row;
now
-> col = symbol[i].col;
if (first == 1 )
{
head
= now;
head
-> next = NULL;
head
-> last = NULL;
p
= head;
end
= p;
first
= 0 ;
}
else
{
now
-> last = p;
p
-> next = now;
p
= now;
end
= p;
p
-> next = NULL;
}
}
_s
++ ;
}
getsum();
if (error)
printf(
" error\n " );
else
printf(
" %d\n " ,sum);
}
return 0 ;
}

你可能感兴趣的:(Matrix)