2 条题解

  • 0
    @ 2025-10-8 17:02:57
    #include <bits/stdc++.h>
    using namespace std;
    const int N = 250010;
    int n, c[N];
    inline void add(int x, int k) { for (; x <= n; x += (x & -x)) c[x] += k; }
    inline int getsum(int x) { int res = 0; for (; x; x -= (x & -x)) res += c[x]; return res; }
    vector<int> G[N];
    int l[N], r[N], tsp;
    // l[i], r[i]分别表示以i为根节点的子树在dfs序中的最左位置和最右位置
    void dfs(int x, int xfa)
    {
        l[x] = ++tsp;
        for (int y : G[x]) if (y != xfa) dfs(y, x);
        r[x] = tsp;
    }
    
    int main()
    {
        scanf("%d", &n);
        for (int i = 1, x, y; i < n; i++) { scanf("%d%d", &x, &y); G[x].push_back(y); G[y].push_back(x); }
        tsp = 0; dfs(1, 0);
        memset(c, 0, sizeof(c));
        for (int i = 2; i <= n; i++)
            add(l[i], 1),
            add(r[i] + 1, -1);
    
        int m; scanf("%d", &m);
        for (int i = 1; i <= m + n - 1; i++)
        {
            char c[2]; scanf("%s", c);
            if (c[0] == 'W')
            {
                int x; scanf("%d", &x);
                printf("%d\n", getsum(l[x]));
            }
            else
            {
                int x, y; scanf("%d%d", &x, &y);
                if (l[x] > l[y]) swap(x, y);
                add(l[y], -1);
                add(r[y] + 1, 1);
            }
        }
        return 0;
    }
    
    • 0
      @ 2025-10-8 17:02:44
      #include<bits/stdc++.h>
      using namespace std;
      const int N = 250010;
      int n, c[N];
      inline void add(int x,int k){for(;x<=n;x+=(x&-x))c[x]+=k;}
      inline int getsum(int x){int res=0;for(;x;x-=(x&-x)) res+=c[x];return res;}
      vector<int>G[N];
      int l[N], r[N],tsp;
      //l[i], r[i]分别表示以i为根节点的子树在dfs序中的最左位置和最右位置
      void dfs(int x, int xfa)
      {
          l[x]=++tsp;
          for(int y:G[x])if(y!=xfa) dfs(y,x);
          r[x]=tsp;
      }
      
      int main()
      {
          scanf("%d", &n);
          for(int i=1,x,y;i<n;i++) {scanf("%d%d", &x, &y); G[x].push_back(y); G[y].push_back(x);}
          tsp=0;dfs(1,0);
      	memset(c, 0, sizeof(c));
          for(int i=2;i<=n;i++)
              add(l[i],1),
      		add(r[i]+1,-1);
      
          int m;scanf("%d", &m);
          for(int i=1;i<=m+n-1;i++)
          {
              char c[2];scanf("%s", c);
              if(c[0]=='W')
              {
                  int x;scanf("%d", &x);
                  printf("%d\n", getsum(l[x]));
              }
              else
              {
                  int x,y;scanf("%d%d",&x,&y);
      			if(l[x]>l[y]) swap(x,y);
                  add(l[y]  , -1);
                  add(r[y]+1,  1);
              }
          }
          return 0;
      }
      
      • 1

      信息

      ID
      2756
      时间
      2000ms
      内存
      64MiB
      难度
      7
      标签
      递交数
      17
      已通过
      9
      上传者