ZOJ - 3872 Beauty of Array
題意:給定一個含有N個數的序列S,定義序列的魅力值為序列中不同數字之和,求出該序列所有子序列的魅力值之和。
分析:每個數乘以它出現的次數,求和即可。
如何求每個數出現的次數?
1、對于一個各數字完全不同的序列,
eg:3 5 2 6 8
對于5來說,確定其存在于的子序列
(1)其右面,可選0個數字---5
?可選1個數字---3 5
(2)其右面,可選0個數字---5
?可選1個數字---5 2
?可選2個數字---5 2 6
? ? ? ?可選3個數字---5 2 6 8
因此,2 * 4 = 8,則5存在于8種子序列中。
2、若序列中出現了重復數字,那么左邊直接處理到該重復數字之前出現的位置后即可。
eg:2 3 3 2
對于第二個3,在計算其存在于的子序列時,只需要考慮3(第二個3) 和 3 2 兩個子序列即可。
原因:2 3 3 2的子序列有
2
3
2 3
3
3 3
2 3 3
2
3 2
3 3 2
2 3 3 2
我現在只要把這些各序列中不同的數字相加即可。
從左往右開始考慮,2存在于4個子序列中,所以將這4個子序列中的2先加起來,還剩下
2
3
2 3
3
3 3
2 3 3
2
3 2
3 3 2
2 3 3 2
同理,3(序列中第一個3)存在于6個子序列中,還剩下
2
3
2?3
3
3 3
2?3 3
2
3 2
3 3 2
2?3 3 2
現在,來考慮第2個3,按照“若序列中出現了重復數字,那么左邊直接處理到該重復數字之前出現的位置后即可”,只需劃掉3 和3 2兩個序列中的3,還剩下
2
3
2?3
3
3?3
2?3?3
2
3 2
3?3 2
2?3?3 2
最后,劃掉最后一個2存在的序列中的這個2,剩下
2
3
2?3
3
3?3
2?3?3
2
3?2
3?3 2
2?3?3 2
其實,求的就是這些劃掉數字的和,因為序列中重復的數字不需要研究呀。
因此,對于序列中出現的第二個3,他出現的序列范圍為啥不是從最左面開始選數字,而是從該數字最后一次出現的位置后選數字,
因為,從最后一次出現的位置前開始選數字,因為那個之前出現過的數字所包含于的序列,已經把那個之前出現過的數字加上了,沒必要再加這個數字了,
eg:
這一段,這第二個3如果從最后一次出現的位置前開始選數字,假設從最左面取吧,那形成的序列是2 3 3,在研究第一個3時,該序列已經加過一個3了,(答案只需要該序列中加一個3就行呀)不需要再加第2個3了,所以沒必要從最后一次出現的位置前選數字。
#include<cstdio> #include<cstring> #include<cstdlib> #include<cctype> #include<cmath> #include<iostream> #include<sstream> #include<iterator> #include<algorithm> #include<string> #include<vector> #include<set> #include<map> #include<stack> #include<deque> #include<queue> #include<list> #define lowbit(x) (x & (-x)) const double eps = 1e-8; inline int dcmp(double a, double b){if(fabs(a - b) < eps) return 0;return a > b ? 1 : -1; } typedef long long LL; typedef unsigned long long ULL; const int INT_INF = 0x3f3f3f3f; const int INT_M_INF = 0x7f7f7f7f; const LL LL_INF = 0x3f3f3f3f3f3f3f3f; const LL LL_M_INF = 0x7f7f7f7f7f7f7f7f; const int dr[] = {0, 0, -1, 1, -1, -1, 1, 1}; const int dc[] = {-1, 1, 0, 0, -1, 1, -1, 1}; const int MOD = 1e9 + 7; const double pi = acos(-1.0); const int MAXN = 1000000 + 10; const int MAXT = 10000 + 10; using namespace std; int last[MAXN]; int main(){int T;scanf("%d", &T);while(T--){int n, x;scanf("%d", &n);memset(last, -1, sizeof last);LL ans = 0;for(int i = 0; i < n; ++i){scanf("%d", &x);ans += x * LL(i - last[x]) * (n - i);last[x] = i;}printf("%lld\n", ans);}return 0; }?
轉載于:https://www.cnblogs.com/tyty-Somnuspoppy/p/6783586.html
總結
以上是生活随笔為你收集整理的ZOJ - 3872 Beauty of Array的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 测试用例设计方法(五)路径覆盖
- 下一篇: ajax原理及其优缺点