ACM_梦中的函数

梦中的函数

Time Limit: 2000/1000ms (Java/Others)

Problem Description:

寒假那段时间,每天刷题的小G连做梦都是代码,于是有了这道题。
给定一个数组a,求g(a),g(a)=∑( a[i]*f(a[i]) )
其中f(x)表示x在数组a中的出现次数,重复数字不重复计算。

Input:

多组数据输入(EOF),每组数据第一行是数组a的大小N(1<=N<=10000),第二行是N个数A1到AN(-10000<=Ai<=10000)

Output:

对于每组测试数据,以"ans"=answer的形式输出答案。

Sample Input:

5
2 23 233 233 2333

Sample Output:

"ans"=2824
解题思路:使用map容器(键:某个数字,值:对应数字出现的次数)简单过,时间复杂度为O(nlogn)。
AC代码:
 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 typedef long long LL;
 4 LL ans;int x,n;map<int,int> mp;
 5 int main(){
 6     while(cin>>n){
 7         mp.clear();ans=0;
 8         while(n--){cin>>x;mp[x]++;}
 9         for(map<int,int>::iterator it=mp.begin();it!=mp.end();++it)
10             ans+=(it->first)*(it->second);//键值的引用
11         cout<<"\"ans\"="<<ans<<endl;
12     }
13     return 0;
14 }

猜你喜欢

转载自www.cnblogs.com/acgoto/p/9240516.html