S-Tree 表示 n 變量布爾函數。輸入:
- 變量排序(如 x3 x1 x2)
- 終端節點值串(長 2^n,對應葉子左到右)
- m 個變量賦值(VVA,如 110 表示 x1=1,x2=1,x3=0)
對每個 VVA 輸出函數值。多測試用例,n=0 結束。
var[depth] = 變量索引(1-based)。leaves。d=0..n-1:idx = var[d],查 VVA 第 idx 位。leaves[pos]。
路徑決策構成二進制數:bit = (vva[var[d]]-'0'),從高位到低位。
最終索引 pos = (bit₀<<(n-1)) | (bit₁<<(n-2)) | ... | bitₙ₋₁。
輸出 leaves[pos]。
#include
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, tc=1;
while(cin>>n, n) {
vector order(n);
for(int i=0;i>s; // x3
order[i] = s[1]-'0'; // 變量索引 1..n
}
string leaves; cin>>leaves; // 長 2^n
int m; cin>>m;
cout << "S-Tree #" << tc++ << ":\n";
while(m--) {
string vva; cin>>vva; // 長 n,vva[0]對應x1
int pos=0;
for(int d=0; d
x3,提取數字 3 即變量索引。i 位對應 x_{i+1},與排序無關。2^n,索引 0 為全 0 路徑(最左葉子)。S-Tree #k: 換行,連續輸出 m 個字符,再空兩行。O(n),n≤ 通常很小(題目未給上限但葉子串 2^n 暗示 n≤5 左右)。
Input:
3
x1 x2 x3
00000111
4
000
010
111
110
3
x3 x1 x2
00010011
4
000
010
111
110
0
Output:
S-Tree #1:
0011
S-Tree #2:
0011
代碼輸出完全匹配。