Hdu 4961 Boring Sum (efficient), hdu4961boringsum
Link: hdu 4961 Boring Sum
Give an ai array;
- Construct bi, k = max (j | 0 <j <I, aj % ai = 0), bi = ak;
- Construct ci, k = min (j | I <j ≤ n, aj % ai = 0), ci = ak;
Calculate Σ I = 1nbi ∗ ci
Solution: Because ai is less than or equal to 105, each number factor is pre-processed. When bi and ci arrays are processed, all the factors are updated each time a number is traversed, the maximum value for bi maintenance and the minimum value for ci maintenance.
#include <cstdio>#include <cstring>#include <vector>#include <algorithm>using namespace std;typedef long long ll;const int maxn = 1e5;const int INF = 0x3f3f3f3f;int n, arr[maxn+5], b[maxn+5], c[maxn+5], v[maxn+5];vector<int> g[maxn+5];void get_factor (int n) { for (int i = 1; i <= n; i++) g[i].clear(); for (int i = 1; i <= n; i++) { for (int j = i; j <= n; j += i) g[j].push_back(i); }}void init () { memset(v, 0, sizeof(v)); for (int i = 1; i <= n; i++) { int u = arr[i]; int k = (v[u] == 0 ? i :v[u]); b[i] = arr[k]; for (int j = 0; j < g[u].size(); j++) v[g[u][j]] = max(v[g[u][j]], i); } memset(v, INF, sizeof(v)); for (int i = n; i >= 1; i--) { int u = arr[i]; int k = (v[u] == INF ? i : v[u]); c[i] = arr[k]; for (int j = 0; j < g[u].size(); j++) v[g[u][j]] = min(v[g[u][j]], i); }}int main () { get_factor(maxn); while (scanf("%d", &n) == 1 && n) { for (int i = 1; i <= n; i++) scanf("%d", &arr[i]); init(); ll ans = 0; for (int i = 1; i <= n; i++) ans = ans + b[i] * 1LL * c[i]; printf("%I64d\n", ans); } return 0;}
Hdu 1003 max sum
# Include <stdio. h>
# Include <stdlib. h>
Int a [100005], sum [100005];
Int main ()
{
Int ca, count = 0;
Scanf ("% d", & ca );
While (ca --)
{
Int n, I;
Scanf ("% d", & n );
For (I = 1; I <= n; I ++)
Scanf ("% d", & a [I]);
Sum [1] = a [1];
Int r = 1, max = a [1];
For (I = 2; I <= n; I ++)
{
If (sum [I-1]> 0)
{
Sum [I] = sum [I-1] + a [I];
If (sum [I]> max)
{
Max = sum [I];
R = I;
}
}
Else
{
Sum [I] = a [I];
If (sum [I]> max)
{
Max = sum [I];
R = I;
}
}
}
Count ++;
For (I = R-1; I> 0; I --)
If (sum [I] <0) break;
Printf ("Case % d: \ n", count );
Printf ("% d \ n", max, I + 1, r );
If (ca! = 0) printf ("\ n ");
}
}
Hdu 1003 Max sum can be used as an example, but it is always wrong answer.
The idea is okay, but you didn't mark the start and end times when calculating the sum, causing the trouble of locating again later. Let's take a look at startP and endP in my ac code.
# Include <stdio. h>
Int main ()
{
Int T, N, I, j, startP, endP, max, num, sum, temp;
Scanf ("% d", & T );
For (j = 0; j <T; j ++)
{
Max =-1001;
Temp = 1; sum = 0;
Scanf ("% d", & N );
For (I = 0; I <N; I ++)
{
Scanf ("% d", & num );
Sum + = num;
If (sum> max)
{
Max = sum;
StartP = temp;
EndP = I + 1;
}
If (sum <0)
{
Sum = 0;
Temp = I + 2;
}
}
Printf ("Case % d: \ n % d \ n", j + 1, max, startP, endP );
If (j <T-1)
Printf ("\ n ");
}
Return 0;
}