hoj 2430 Counting the algorithms

 
  

Counting the algorithms

 
  
My Tags   (Edit)
 
  
  Source : mostleg
  Time limit : 1 sec   Memory limit : 64 M

Submitted : 484, Accepted : 186

 
  

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 3is 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=1marks. Therefore, in total you get 5+3+1=9 and that is the best strategy.


题意:给出2*N的序列,每个数∈[1,N]出现2次  2个数之间的间隔为得分,
  求得一个得分后会删除这两个数,问最大得分
N比较大,应该是贪心
  从后往前删除数,用树状数组求得sum(x)个数
    对于嵌套的、相互独立的,先删除谁都没关系
    但对于包含关系的,必须先删除外围的,所以从后开始(从前开始也一样)#include <stdio.h>
#include <string.h> #define maxn  200500 int c[maxn],be[maxn],en[maxn],a[maxn]; int n; int lowbit( int x) {  return x&(-x); } void updata( int N,int p) {     while(N<=2*n)   {         c[N]+=p;N+=lowbit(N);   } } int sum( int x) {   int s=0;   while(x!=0)   {         s+=c[x];x-=lowbit(x);   }   return s; } int main( ) {  int i;  while(scanf("%d",&n)!=EOF)  {         memset(be,0,sizeof(be));    for( i=1;i<=2*n;i++)    {          scanf("%d",&a[i]);          if(be[a[i]]) en[a[i]]=i;          else be[a[i]]=i;          updata(i,1);    }    int ans=0;    for(i=2*n;i>=1;i--)    {          if(be[a[i]]==0) continue;          ans+=sum(i)-sum(be[a[i]]);          updata(be[a[i]],-1);          updata(i,-1);          be[a[i]]=0;    }    printf("%d\n",ans);  }  return 0; }
链接:http://acm.hit.edu.cn/hoj/problem/view?id=2430

你可能感兴趣的:(algorithms)