Official

B - Various distances Editorial by kyopro_friends


問題文に書かれた通りの計算式に従って計算を行い、結果を出力すればよいです。絶対値、平方根、最大値などは、ほとんどの言語では標準関数として用意されているので、使い方を確認しておきましょう。

回答例(C++)

#include <bits/stdc++.h>
using namespace std;
 
int main(){
	cout << fixed << setprecision(15);

	int n;
	cin >> n;
	vector<int>x(n);
	for(int i=0;i<n;i++)cin >> x[i];

	long ans1=0;
	for(int i=0;i<n;i++)ans1+=abs(x[i]);
	cout << ans1 << endl;

	long ans2=0;
	for(int i=0;i<n;i++)ans2+=abs(x[i])*(long)abs(x[i]);
	cout << sqrt(ans2) << endl;

	int ans3=0;
	for(int i=0;i<n;i++)ans3=max(ans3,abs(x[i]));
	cout << ans3 << endl;
}

オーバーフローや誤差(出力形式)に注意してください。

オーバーフローについて

32bit符号付き整数型(例えばAtCoder環境でのC/C++のint型)では、\(2^{31} \fallingdotseq 2.1\times 10^9\) 以上の値を表現できません。かわりに、64bit符号付き整数型(例えばAtCoder環境でのC/C++のlong型)などを使う必要があります。

C++クイズ:以下の4つの計算の内、正しく「10000000000」が出力されるものがいくつあるでしょうか?

#include <bits/stdc++.h>
using namespace std;

int main(){
	cout << (100000 * 100000) << endl;
	int x=100000;
	cout << (x*x) << endl;
	long y=x*x;
	cout << y << endl;
	long z=x*(long)x;
	cout << z << endl;	
}

誤差について

倍精度浮動小数点数(例えばAtCoder環境でのC/C++のdouble型)は10進数で15桁から16桁の精度があります。大抵の問題は誤差を気にせずに計算してもうまくいきますが、気を付けましょう。

例題1

例題2

また計算自体は正しく行われていても、出力桁数が不足しているためWAになることがあり得ます。各言語で、出力桁数の設定方法を確認しましょう

#include <bits/stdc++.h>
using namespace std;

int main(){
	cout << 0.1234567890123;  //AtCoder環境では0.123457になる
}

posted:
last update: