ZOJ-3872-Beauty of Array【数学】【12th浙江省赛】
2016-01-27 00:00
399 查看
ZOJ-3872-Beauty of Array
[code] Time Limit: 2 Seconds Memory Limit: 65536 KB
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
题目链接:ZOJ-3872
题目大意:给出n个数字的序列,求所有连续的子序列,不同数字的和。
题目思路:dp[i] //表示以数字i结尾的子序列的和
dp[i] = dp[i - 1] + (i - pos[num[i]]) * num[i]; //dp[i]等于以i-1结尾的子序列的和,加上把前面(i - pos[num[i]])个子序列后面都加上num[i].
eg: 1 2 3 4 | 2
以最后一个2结尾的子序列和为例,(一个子序列中出现相同数字,该数字只加一次)
[code]1 + 2 + 3 + 4 + 2, (前面出现过2,所以最后一个2不加) 2 + 3 + 4 + 2, 3 + 4 + 2, (前面没出现过2,最后一个2加) 4 + 2,= 2,
pos[num[i]] //记录上一次出现num[i]的位置。
以下是代码:
[code]#include <vector> #include <map> #include <set> #include <algorithm> #include <iostream> #include <cstdio> #include <cmath> #include <cstdlib> #include <string> #include <cstring> using namespace std; int num[100010]; int pos[100010]; long long dp[100010]; //以i结尾的和 int main(){ int t; cin >> t; while(t--) { int n; scanf("%d",&n); memset(num,0,sizeof(num)); memset(pos,-1,sizeof(pos)); memset(dp,0,sizeof(dp)); for (int i = 0; i < n; i++) { cin >> num[i]; } dp[0] = num[0]; pos[num[0]] = 0; for (int i = 1; i < n; i++) { dp[i] = dp[i - 1] + (i - pos[num[i]]) * num[i]; pos[num[i]] = i; //更新i最后一次出现的位置 } long long ans = 0; for (int i = 0; i < n; i++) { ans += dp[i]; //各个结尾的和即为答案 } cout << ans << endl; } return 0; }
相关文章推荐
- 手机号码实名制认证接口
- VIEWGOOD(远古)流媒体技术在部队中的应用
- eclipse中修改默认的文件编码
- vSphere虚拟化环境中存储与网路的概念_vSphere虚拟化入门到精通
- 跨平台室内三维地图引擎——FengMap公开测试
- 程序员遇到BUG后,最好的方法是?
- 宏正ATEN发行新款机架型PS/2与USB双界面KVM多电脑切换器
- 点击修改背景颜色
- select+onchange事件详解
- what is the time
- 1.学习流程图
- 2.整个开发app流程
- iOS定位,两地之间距离,编码与反编码
- volatile关键字
- java 切割时间,提取时间中的年月日
- 费马小定理 素数判定 蒙哥马利算法
- 异步加载
- 混迹于IT纯屌界中独一无二的丸子
- Oracle RAC 11g监听配置特征
- 在docker上搭建hadoop single node cluster