[NYOJ] [1121] Triangular Sums

Problem Description

Loading...

Problem Analysis

There is a lot of repeated computation
so I figured precomputing a table would be better

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
#include<stdio.h>
int main() {
	int T,kase=0;
	scanf("%d",&T);
	int a[320]= {0,3};
	int b[320]= {0,3};
	for(int i=2; i<320; i++) {
		a[i]=i*(a[i-1]/(i-1)+i+1);
	}
	for(int i=2; i<320; i++) {
		b[i]=b[i-1]+a[i];
	}
	while(T--) {
		int n;
		scanf("%d",&n);
		printf("%d %d %d\n",++kase,n,b[n]);
	}
	return 0;
}

The reference solution uses only one table
it probably worked backwards from the result when spotting the pattern

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
#include<iostream>
using namespace std;
const int M=310;
int W[M];
int main() {
	for(int i=1; i!=M; i++)
		W[i]=W[i-1]+i*(i+1)*(i+2)/2;
	int m,n;
	cin>>n;
	for(int i=1; i<=n; i++) {
		cin>>m;
		cout<<i<<" "<<m<<" "<<W[m]<<endl;
	}
}

Problem record: Triangular Sums

This post is licensed under CC BY-NC-SA 4.0. If it helped, or if you have anything to say, the comment box below is open.
Page views —
Unique visitors —

Loading...