第十七届浙大城市学院程序设计竞赛(同步赛)B-Sumo and His Followers

Sumo and His Followers
链接:https://ac.nowcoder.com/acm/contest/5954/B
来源:牛客网
思路:
考虑一组简单的情况:

1
5
1 2 3 4 5

答案为:(1 * 4 + 2 * 3+ 3 * 2 + 4 * 1 + 5 * 0) / 5 = 4
思路很明显,使用前缀和即可`

#include
using namespace std;
const int maxn=1e5+5;
bool cmp(int a,int b){
	return a<b;
}
int a[maxn];
int main(){
	int T;
	cin>>T;
	while(T--){
		int n;
		cin>>n;
		for(int i=1;i<=n;i++){
			cin>>a[i];
		}
		sort(a+1,a+1+n,cmp);	
		long long sum=0;
		for(int i=1;i<=n-1;i++){
		a[i]+=a[i-1];
		//cout<
		sum+=a[i];
		}
		double r=sum*1.0/n;	
		cout<<setprecision(2)<<fixed<<r<<endl;
	}
	return 0;
}

还有一种方法:(模拟推出的公式)

#include
using namespace std;
const int maxn=1e5+5;
bool cmp(int a,int b){
	return a<b;
}
int a[maxn];
int main(){
	int T;
	cin>>T;
	while(T--){
		int n;
		cin>>n;
		for(int i=1;i<=n;i++){
			cin>>a[i];
		}
		sort(a+1,a+1+n,cmp);	
		long long sum=0;
		for(int i=1;i<=n-1;i++){
			sum+=(n-i)*a[i];
		}
		double r=sum*1.0/n;	
		cout<<setprecision(2)<<fixed<<r<<endl;
	}
	return 0;
}

你可能感兴趣的:(编程练习)