http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=1011
简单题,DFS
#include <iostream>
#include <string.h>
#include <vector>
#include <math.h>
#include <stdio.h>
using namespace std;
vector< pair<int, int> > matrix[15][10];
int n, m, k;
int NTA;
bool DFS(char root[], int current, int signal)
{
int left = current * 2, right = left + 1;
vector< pair<int, int> > tranList = matrix[signal][root[current] - 'a'];
if (root[left] != '*' && root[right] != '*')
{
for (int i = 0; i < tranList.size(); i++)
if (DFS(root, left, tranList[i].first) && DFS(root, right, tranList[i].second))
return true;
return false;
}
else if (root[left] != '*' && root[right] == '*')
{
for (int i = 0; i < tranList.size(); i++)
if (DFS(root, left, tranList[i].first))
return true;
return false;
}
else if (root[left] == '*' && root[right] != '*')
{
for (int i = 0; i < tranList.size(); i++)
if (DFS(root, right, tranList[i].second))
return true;
return false;
}
else // leaf node
{
for (int i = 0; i < tranList.size(); i++)
if (tranList[i].first >= (n - m) && tranList[i].second >= (n - m))
return true;
return false;
}
}
int main()
{
char c;
int NTAIndex = 1;
while (cin >> n >> m >> k)
{
if (n == 0 && m == 0 && k == 0)
break;
getchar(); // read newline character
for (int i = 0; i < n; i++)
for (int j = 0; j < k; j++)
{
int num = 0;
vector<int> v;
while (true)
{
c = getchar();
if (c == ' ')
{
v.push_back(num);
num = 0;
}
else if (c == '\n')
{
v.push_back(num);
matrix[i][j].clear();
for(int p = 0; p < v.size(); p += 2)
matrix[i][j].push_back(make_pair<int, int>(v[p], v[p+1]));
break;
}
else
{
num = 10 * num + c - '0';
}
}
}
if (NTAIndex > 1)
cout << endl;
printf("NTA%d:\n", NTAIndex++);
while (cin >> NTA)
{
if (NTA == -1)
break;
getchar(); // read newline character
char tree[2048]; // 10 level, taotal 2^11=2048 elements
memset(tree, '*', sizeof(tree));
for (int i = 1; i < pow(2.0, NTA + 1); i++)
cin >> tree[i];
if(DFS(tree, 1, 0))
cout << "Valid" << endl;
else
cout << "Invalid" << endl;
}
}
}