BZOJ 1106 [POI2007]立方体大作战tet

本文介绍了一种利用树状数组实现的贪心算法解决特定问题的方法。通过遍历数组并利用树状数组进行维护,确保了在遇到可合并元素时能够高效地计算结果。适用于处理一系列数字中寻找最优合并顺序的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接

https://www.lydsy.com/JudgeOnline/problem.php?id=1106

思路

贪心,如果出现了下面情况:

1 2 2 1

那么显然先合并22,再合并11.

如果是下面的情况:

1 2 1 2

那么合并11和合并22的顺序是无关紧要的。

一遍从左扫到右,找到两个相同点就合并,用树状数组维护一下就好了。

代码

#include <cstdio>

const int maxn=100000;

int read()
{
  int x=0,f=1;
  char ch=getchar();
  while((ch<'0')||(ch>'9'))
    {
      if(ch=='-')
        {
          f=-f;
        }
      ch=getchar();
    }
  while((ch>='0')&&(ch<='9'))
    {
      x=x*10+ch-'0';
      ch=getchar();
    }
  return x*f;
}

int n,a,ans,pre[maxn+10];

namespace tree_array
{
  int c[maxn+10];

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

  inline int add(int pos,int x)
  {
    while(pos<=n)
      {
        c[pos]+=x;
        pos+=lowbit(pos);
      }
    return 0;
  }

  inline int sum(int pos)
  {
    int res=0;
    while(pos)
      {
        res+=c[pos];
        pos-=lowbit(pos);
      }
    return res;
  }
}

int main()
{
  n=read()<<1;
  for(register int i=1; i<=n; ++i)
    {
      a=read();
      if(!pre[a])
        {
          pre[a]=i;
          tree_array::add(i,1);
        }
      else
        {
          ans+=tree_array::sum(i)-tree_array::sum(pre[a]-1)-1;
          tree_array::add(pre[a],-1);
        }
    }
  printf("%d\n",ans);
  return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值