Problem B - abc375
Problem Link: B - Traveling Takahashi Problem (AtCoder Beginner Contest 375)
Approach
The code takes a list of points and calculates the total distance between them. It first reads the points, adds the origin (0,0) at the start, reverses the list, adds origin at end again, updates the size of n and and then computes the distance between each pair of consecutive points. Finally, it prints the total distance with precision 20.
Code Implementation
#include <bits/stdc++.h>
#define int long long
#define endl '\n'
using namespace std;
signed main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int t=1;
// cin >> t;
while (t--) {
int n;
cin >> n;
vector<pair<int, int>> v(n);
for (auto &x:v){
cin >> x.first >> x.second;
}
v.emplace_back(0,0);
reverse(v.begin(),v.end());
v.emplace_back(0,0);
n=size(v);
long double ans=0;
for (int i=0; i+1<n; i++) {
const int x=v[i].first-v[i+1].first, y=v[i].second-v[i+1].second;
ans+=sqrt(x*x+y*y);
}
cout << fixed << setprecision(20) << ans << endl;
}
return 0;
}
import math
def solve():
n = int(input())
points = []
for _ in range(n):
points.append(list(map(int, input().split())))
# Add origin at start and end
# Note: The C++ solution logic effectively adds origin at both ends
# (indirectly via reverse logic), here is the direct equivalent:
path = [[0, 0]] + points + [[0, 0]]
ans = 0.0
for i in range(len(path) - 1):
x1, y1 = path[i]
x2, y2 = path[i+1]
dx = x1 - x2
dy = y1 - y2
ans += math.sqrt(dx*dx + dy*dy)
print(f"{ans:.20f}")
if __name__ == "__main__":
solve()