uva712_S樹


///////////////////////////////////////////////////////////////////////////////////////////////////////
作者:tt2767
聲明:本文遵循以下協議自由轉載-非商用-非衍生-保持署名|Creative Commons BY-NC-ND 3.0
查看本文更新與討論請點擊:http://blog.csdn.net/tt2767
鏈接被刪請百度: CSDN tt2767
///////////////////////////////////////////////////////////////////////////////////////////////////////


題解:
把查詢的值看成二進制,轉換成十進制之後去葉子裏面找對應的值輸出即可

#include<cstdio>
#include<cstring>
#include<iostream>

const int N = 100009;

int change(char * s);
//pow調用庫中的也可,由於可能存在的精度問題,重寫了一下
int pow(int x, int y);
void rev(char * x);
int main()
{
    int n, m, tot = 1;

    while(scanf("%d", &n) == 1 && n)
    {
        getchar();
        int  p = 0 ;
        char s[N], ans[N], x[N];
        gets(s);
        gets(s);
        scanf("%d", &m);

        getchar();

        while(m--)
        {
            gets(x);
            ans[p++] = s[change(x)];
        }

        ans[p] = '\0';
        printf("S-Tree #%d:\n", tot++);
        puts(ans);
        puts("");
    }

    return 0;
}

int change(char * s)
{
    rev(s);
    int l  = strlen(s);
    int ans = 0, p = 0;
    for(int i = 0 ; i < l ; i++)
        ans+= (s[i]-'0') * pow(2,i);
    return ans;
}

int pow(int x, int y)
{
    int ans = 1;

    while(y--)
    {
        ans *= x;
    }
    return ans;
}

void rev(char * x)
{
    int right = strlen(x)-1;
    int left = 0;
    char temp;

    while(left < right)
    {
        temp = x[left];
        x[left++] = x[right];
        x[right--] = temp;
    }
}
發佈了50 篇原創文章 · 獲贊 9 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章