NC252122. Interconnection
描述
输入描述
The first line contains an integer , denoting the number of villages.
The second line contains integers , where denotes the maximum number of roads that village can participate in building.
输出描述
Output a single integer, which is the minimum cost to make all villages reachable to each other via roads.
If it is impossible, then output "-1".
示例1
输入:
3 2 2 2
输出:
15
示例2
输入:
3 1 1 1
输出:
-1
说明:
For the first example, the built roads are and . Thus the cost is .C 解法, 执行用时: 31ms, 内存消耗: 1888K, 提交时间: 2023-05-20 14:36:09
#include <stdio.h> long long a[200010]; int main () { long long n,i,sum=0,ans=0; scanf("%lld",&n); for(i=1;i<=n;i++) { scanf("%lld",&a[i]); sum+=a[i]; } sum-=n*2-2; if(sum<0) { printf("-1"); return 0; } for(i=n;i>=1;i--) { if(sum) { if(sum>=a[i]-1) { sum-=a[i]-1; ans+=i*i; } else { ans+=i*i*(a[i]-sum); sum=0; } } else ans+=i*i*a[i]; } printf("%lld",ans); return 0; }
pypy3 解法, 执行用时: 169ms, 内存消耗: 41896K, 提交时间: 2023-05-22 23:22:05
n = int(input()) d = list(map(int, input().split())) flag = 0 ans = 0 for i in range(n): d[i] -= 1 if d[i] < 0: flag = 1 ans += (i + 1) ** 2 pos = 0 for i in range(n - 2): while pos < n-1 and d[pos] <= 0: pos += 1 if pos >= n: break ans += (pos + 1) ** 2 d[pos] -= 1 if d[pos] < 0: flag = 1 if flag: print(-1) else: print(ans)
C++(g++ 7.5.0) 解法, 执行用时: 509ms, 内存消耗: 2032K, 提交时间: 2023-05-22 09:03:57
#include<bits/stdc++.h> using namespace std; const int MAX=2*1e5+5; typedef long long ll; ll a[MAX]; int main(){ ll n; cin>>n; ll tmp=2*(n-1),sum=0; for(ll i=1;i<=n;i++) cin>>a[i],sum+=a[i]; if(sum<tmp) cout<<"-1\n"; else{ for(ll i=n;i>=1;i--){ while(a[i]>1&&sum>tmp) sum--,a[i]--; } ll res=0; for(ll i=1;i<=n;i++){ res+=a[i]*i*i; } cout<<res<<endl; } return 0; }
Python3 解法, 执行用时: 204ms, 内存消耗: 27640K, 提交时间: 2023-06-28 17:34:02
n = int(input()) arr = list(map(int, input().split(' '))) if sum(arr) < (n - 1) * 2: print(-1) else: ans = n * (n + 1) * (n + n + 1) // 6 cnt = n - 2 for i, num in enumerate(arr, 1): tmp = min(cnt, num - 1) cnt -= tmp ans += i * i * tmp if cnt == 0: break print(ans)
C++(clang++ 11.0.1) 解法, 执行用时: 49ms, 内存消耗: 420K, 提交时间: 2023-06-02 10:55:40
#include<bits/stdc++.h> using namespace std; const int N=2e5+10; typedef long long ll; int n; int main(){ cin>>n; int sum=0; ll res=0; for(int i=1;i<=n;i++){ int d; cin>>d; int u=min(d-1,(n-1)*2-n-sum);res+=(ll)(u+1)*i*i; sum+=u;} if(sum<(n-1)*2-n) puts("-1");else cout<<res<<endl; return 0; }