UVa712 S-Trees

9960 단어 tree
// UVa712 S-Trees
// Rujia Liu
//   :       ,       01  , 0    , 1    。        ,      (       ),          
//   :         1, 2, 3, ...       2,     2 1。         2^n
#include<iostream>
#include<string>
using namespace std;

const int maxn = 10;
int n, v[maxn];//   
string leaves;

int solve(const string& q) {
  int u = 1;
  for(int i = 0; i < n; i++) {
    if(q[v[i]] == '0') u *= 2; else u = u*2+1;
  }
  return leaves[u-(1<<n)] - '0';
}

int main() {
  int kase = 0;
  while(cin >> n && n) {
    string s;
    cout << "S-Tree #" << ++kase << ":
"; for(int i = 0; i < n; i++) { cin >> s; v[i] = s[1] - '1'; } int m; cin >> leaves >> m; while(m--) { string q; cin >> q; cout << solve(q); } cout << "

"; } return 0; }

나의 해답:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
//0 left, 1 right

const int N=10;
char leaves[1<<N];
//     
int order[N];
int n;

void solve(char* buf)
{
        //        ( 1  )
        int j=1;
        for(int i=0;i<n;i++)
        {
                if(buf[order[i]]=='0')
                        j*=2;
                else
                        j=j*2+1;
        }
        printf("%c", leaves[j-(1<<n)]);
}

void getorder(char* s)
{
        for(int i=0;i<n;i++)
        {
                order[i]=s[1+3*i]-'1';
        }
}

int main()
{
        //freopen("./uva712.in", "r", stdin);
        char buf[N*3+1];
        int cnt=0;
        while(scanf("%d", &n)==1 && n)
        {
                printf("S-Tree #%d:
", ++cnt); gets(buf);//read line gets(buf);//x1 x2 ... getorder(buf); gets(leaves); int m; scanf("%d", &m); gets(buf);//read line for(int i=0;i<m;i++) { gets(buf); solve(buf); } printf("

"); } return 0; }

좋은 웹페이지 즐겨찾기