ACM-水題 Beauty of Array

題目:

Description

Edward has an array A with N integers. He defines the beauty of an array as the summation of all distinct integers in the array. Now Edward wants to know the summation of the beauty of all contiguous subarray of the array A.

Input

There are multiple test cases. The first line of input contains an integer T indicating the number of test cases. For each test case:

The first line contains an integer N (1 <= N <= 100000), which indicates the size of the array. The next line contains N positive integers separated by spaces. Every integer is no larger than 1000000.

Output

For each case, print the answer in one line.

Sample Input

3
5
1 2 3 4 5
3
2 3 3
4
2 3 3 2

Sample Output

105
21
38

【題目大意】定義Beauty數是一個序列裏所有不相同的數的和,求一個序列所有字序列的Beauty和

  1 <= N <= 100000

解題思路】由於數據比較大,常規方法求字序列和肯定是行不通的,我們不妨這樣想:因爲要區別於不同的數

,可以看成序列裏的數是一個一個加進去的,每次加入一個數,統計前面序列裏第一次出現新加入的這個數的位置,表達的不好,

舉個例子:

1 2 3

定義dp(當前元素前面(包括自己)所有包含自己的字序列的和)

定義sum(當前元素前面所有字序列的和,包括此元素)

//輸入   1     2     3

//dp      1     5     14

//sum   1     6      20

//a[i]      1     2      3



代碼:

#include <iostream>
#include <cstring>
#include<stdio.h>
using namespace std;
const int MAXN = 1e5 + 10;
int main()
{
    int a[MAXN];
    int t, n;
    scanf ("%d", &t);
    while (t--)
    {
        memset (a, 0, sizeof (a));
        scanf ("%d", &n);
        int x;    long long dp = 0, sum = 0;
        for (int i=1; i<=n; ++i)
        {
            scanf ("%d", &x);
            dp = (i - a[x]) * x + dp;
            sum += dp;
            a[x] = i;
        }
        printf ("%lld\n", sum);
    }
    return 0;
}

用MAP:





#include<stdio.h>
#include<iostream>
#include<map>
using namespace std;
map<int, long long int> mark;
int main()
{
    int T, a, n;
    scanf("%d", &T);
    while(T--)
    {
        scanf("%d", &n);
        long long int sum = 0, ans = 0;
        mark.clear();
        for(int i = 1; i <= n; i++)
        {
            scanf("%d", &a);
            ans += (i*a);
            sum += ans;
            sum -= (mark[a] * a);
            ans -= (mark[a] * a);
            mark[a] = i;
       //     cout<<"               "<<sum<<"              "<<ans<<endl;
        }
      //    map<int, long long int>::iterator  iter;
      //   for(iter = mark.begin(); iter != mark.end(); iter++)
     //    {
     //      cout<<iter->first<<"  "<<iter->second<<endl;
    //    }
        printf("%lld\n", sum);
    }
}
知識點:

C++中map容器的說明和使用技巧

http://www.cnblogs.com/anywei/archive/2011/10/27/2226830.html

map的詳細用法

http://blog.csdn.net/sunshinewave/article/details/8067862




發佈了312 篇原創文章 · 獲贊 5 · 訪問量 19萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章