POJ3321Apple Tree【dfs 樹狀數組】

來源:互聯網
上載者:User

標籤:io   os   ar   for   sp   art   問題   c   amp   

題目大意:一棵樹(不一定是二叉樹!!),樹的節點上本來都有一個蘋果,要求完成以下操作:

1.指定某個節點,如果這個節點原本有蘋果則拿去,如果沒有蘋果則填上一個蘋果

2.詢問某個節點以及其子樹一共有多少個蘋果

思路:dfs這棵樹,記錄下第一次到達這個節點的時間以及遍曆離開的時間,於是一個節點就成了一個區間,左端點和右端點分別是開始遍曆的時間和結束遍曆的時間,區間裡夾著的就是這個節點的子樹!!區間端點記錄有沒有蘋果,這樣問題就變成了詢問一個區間和的問題,而加減蘋果就是對區間端點+1和-1 這兩個操作都能用樹狀數組解決

 

#include<cstdio>

#include<string.h>

#include<iostream>

#define maxn 200009

using namespace std;

intnow=0,tree[maxn]={0},n,next[maxn]={0},root[maxn]={0},edge[maxn]={0},start[maxn]={0},end[maxn]={0};

int lowbit(int x){return x &(-x);}

 

void add(int x,int c)

{

   while (x<=2*n)

    {

       tree[x]+=c;

       x+=lowbit(x);

    }

}

int get(int x)

{

   int sum=0;

   for(int i=x;i>=1;i=i-lowbit(i))sum+=tree[i];

   return sum;

}

void addedge(int x,int y)

{

   next[++now]=root[x];

   edge[now]=y;

   root[x]=now;

}

void dfs(int j)

{

   start[j]=++now;

   for(int i=root[j];i!=0;i=next[i])dfs(edge[i]);

   end[j]=++now;

}

int main()

{

   int x,y,m,ope,flag;

   char ch[2];

   scanf("%d",&n);

   for(int i=1;i<=n-1;i++)

    {

       scanf("%d%d",&x,&y);

       addedge(x,y);

    }

   now=0;

   dfs(1);

   for(int i=1;i<=2*n;i++)

   add(i,1);

   scanf("%d",&m);

   for(int i=1;i<=m;i++)

    {

       scanf("%s%d",ch,&ope);

       if (ch[0]==‘Q‘)

        {

           printf("%d\n",(get(end[ope])-get(start[ope]-1))>>1);

       }

       else

       {

           flag=get(end[ope])-get(end[ope]-1);

           if (flag==1)flag=-1;else flag=1;

           add(start[ope],flag);

           add(end[ope],flag);

       }

    }

   return 0;

}

 

調試結果:1次AC

POJ3321Apple Tree【dfs 樹狀數組】

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.