[UVA][math] 10854 - Number of Paths
Number of Paths |
Background
Although testing is a technique which does not allow us to prove the correctness of a program, it is used to assess its reliability, thus increasing our confidence in its correctness. In the literature, there are many testing methods to select test cases which are applied as an input to the program.
The Problem
A programmer has the intention of testing a program. With this aim in mind, he needs to know how many test cases he should obtain such that each distinct path of execution is covered with a test case. Your task is to write a program which computes the number of different paths of execution from the initial sentence to the final sentence, in a given program P.
The Input
The first line of the input contains the number of programs. Subsequently, each program is listed. Each program consists of a set of sentences with a keyword per line. The program finishes with the keyword ENDPROGRAM
There are only two types of sentences: conditional and non-conditional. A non-conditional sentence is represented by means of the keyword S. A conditional sentence is represented by the keywords IF, ELSE and END_IF. The condition of the IF sentence is omitted (i.e., only the IF keyword appears) and it is supposed that all IF sentences have a corresponding ELSE. So, for example, the shortest program with a conditional sentence would be:
IF ELSE END_IF ENDPROGRAM
which has 2 paths of execution.
The Output
For every program you are to print a line containing the number N of different paths of execution. It is supposed that N is never greater than 2^32.
Sample Input
4 IF ELSE END_IF ENDPROGRAM IF S ELSE END_IF IF ELSE S END_IF ENDPROGRAM S S S ENDPROGRAM S IF S S ELSE IF IF S ELSE S END_IF S ELSE S END_IF END_IF S ENDPROGRAM
Sample Output
2 4 1 4
題目描述:
給定 IF, ELSE, END_IF 指令,問程式流程的路徑有多少種?
題目解法:
獨立的巢狀迴圈在同一 BLOCK 中,方法數是相乘起來的。
然而 IF 對應的 ELSE 區塊的方法數是相加起來的。
每個 IF 一定存在對應的 ELSE,其實 S 指令是可以被忽略的,並沒有太多功用。
抓 BUG 抓到死,一直 WA。
#include <stdio.h>
#include <string.h>
char stmt[10005][100];
int n, i;
long long calc() {
long long ret = 0, tmp = 0;
if(!strcmp(stmt[i], "IF")) {
i++;
tmp = 1;
while(true) {
if(!strcmp(stmt[i], "IF"))
tmp *= calc();
else
break;
}
ret += tmp;
}
if(!strcmp(stmt[i], "ELSE")) {
i++;
tmp = 1;
while(true) {
if(!strcmp(stmt[i], "IF"))
tmp *= calc();
else
break;
}
ret += tmp;
}
i++;
return ret;
}
int main() {
int testcase;
scanf("%d", &testcase);
while(testcase--) {
n = 0;
while(scanf("%s", &stmt[n]) == 1) {
if(!strcmp(stmt[n], "ENDPROGRAM"))
break;
if(!strcmp(stmt[n], "IF"))
n++;
else if(!strcmp(stmt[n], "ELSE"))
n++;
else if(!strcmp(stmt[n], "END_IF"))
n++;
}
n++;
i = 0;
long long ret = 1;
while(i < n-1)
ret *= calc();
printf("%lld\n", ret);
}
return 0;
}