Counting the algorithms
Source : mostleg | |||
Time limit : 1 sec | Memory limit : 64 M |
Submitted : 492, Accepted : 190
As most of the ACMers, wy's next target is algorithms, too. wy is clever, so he can learn most of the algorithms quickly. After a short time, he has learned a lot. One day, mostleg asked him that how many he had learned. That was really a hard problem, so wy wanted to change to count other things to distract mostleg's attention. The following problem will tell you what wy counted.
Given 2N integers in a line, in which each integer in the range from 1 to N will appear exactly twice. You job is to choose one integer each time and erase the two of its appearances and get a mark calculated by the differece of there position. For example, if the first 3 is in position 86 and the second 3 is in position 88, you can get 2 marks if you choose to erase 3 at this time. You should notice that after one turn of erasing, integers' positions may change, that is, vacant positions (without integer) in front of non-vacant positions is not allowed.
Input
There are multiply test cases. Each test case contains two lines.
The first line: one integer N(1 <= N <= 100000).
The second line: 2N integers. You can assume that each integer in [1,N] will appear just twice.
Output
One line for each test case, the maximum mark you can get.
Sample Input
3 1 2 3 1 2 3 3 1 2 3 3 2 1
Sample Output
6 9
Hint
We can explain the second sample as this. First, erase 1, you get 6-1=5 marks. Then erase 2, you get 4-1=3 marks. You may notice that in the beginning, the two 2s are at positions 2 and 5, but at this time, they are at positions 1 and 4. At last erase 3, you get 2-1=1 marks. Therefore, in total you get 5+3+1=9 and that is the best strategy.
思路:
从后往前不断删除(这样的话不存在区间包含问题),统计相同元素区间内数的个数。之后将这两个元素一起删除。
代码:
#include<stdio.h>
#include<string.h>
#include<map>
using namespace std;
#define N 100005
#define lowbit(a) (a&(-a))
map<int ,int > mp;
int hash[2*N+1];//hash[i]表示编号为i的所管辖的数的数目;
int a[2*N+1]; //存放数;
int n;
void update(int a,int b)
{
while(a<=2*N)
{
hash[a]+=b;
a+=lowbit(a);
}
}
int getsum(int x)
{
int sum=0;
while(x)
{
sum+=hash[x];
x-=lowbit(x);
}
return sum;
}
int main()
{
while(scanf("%d",&n)!=-1)
{
memset(hash,0,sizeof(hash));
mp.clear();
n+=n;
for(int i=1;i<=n;i++)//从左到右;
{
scanf("%d",&a[i]);
update(i,1);
if(mp.find(a[i])==mp.end())//表示mp中找不到a[i];
mp[a[i]]=i;//编号初始化;
}
int sum=0;
for(int i=n;i>0;i--)//从右到左;
{
if(mp.find(a[i])==mp.end())
continue;
int k=getsum(mp[a[i]]);
sum+=getsum(i)-k;
update(i,-1);
update(mp[a[i]],-1);
mp.erase(a[i]);
}
printf("%d\n",sum);
}
return 0;
}