2017多校第七場02(思維題目)

Build a tree

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 524288/524288 K (Java/Others)
Total Submission(s): 781    Accepted Submission(s): 285


Problem Description
HazelFan wants to build a rooted tree. The tree has n nodes labeled 0 to n1, and the father of the node labeled i is the node labeled i1k. HazelFan wonders the size of every subtree, and you just need to tell him the XOR value of these answers.
 

Input
The first line contains a positive integer T(1T5), denoting the number of test cases.
For each test case:
A single line contains two positive integers n,k(1n,k1018).
 

Output
For each test case:
A single line contains a nonnegative integer, denoting the answer.
 

Sample Input
2 5 2 5 3
 

Sample Output
7 6
 
思維題目,亦或奇數爲1偶數0,然後模擬就可以了。long long 的最大大概是9e18.
代碼:
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll quick(ll a,ll b)
{
    ll ret=1;
    while(b)
    {
        if(b&1)
            ret*=a;
        b>>=1;
        a*=a;
    }
    return ret;
}
int main()
{
//    int s=1;
//    for(int i=2; i<20; i++)
//        s^=i,printf("%d %d\n",i,s);
    int t;
    scanf("%d",&t);
    while(t--)
    {
        ll n,k;
        scanf("%I64d%I64d",&n,&k);
        if(k==1)
        {
            if(n%4==0)
                printf("%I64d\n",n);
            else if(n%4==1)
            {
                printf("1\n");
            }
            else  if(n%4==2)
                printf("%I64d\n",n+1);
            else
                printf("0\n");
            continue;
        }
        ll ans=1,h=0,anss=1;

        while(n>=anss)
        {
            ans*=k;
            anss+=ans;
            h++;
        }
        ll yu=n-(anss-ans),sum,w=k;
        if(yu&1)
            sum=1;
        else
            sum=0;
        ll t=1;
        ll cun=k;
        for(ll i=h; i>0; i--)
        {
            ll geshu=quick(k,i-1);
            ll duo=yu/w;
            ll zhong =yu-duo*w;
            ll r=geshu-duo-1;
            ll tt=t+w;
            ll ttt=t+zhong;
            if(duo&1)
                sum^=tt;
            sum^=ttt;
            if(r&1)
                sum^=(t);
//            if(!t)
//                t=1;
            t+=cun;
            cun*=k;
            w*=k;
        }
        printf("%I64d\n",sum);
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章