PAT頂級題解目錄
Given a positive integer N, let us define a subnumber of N as a consecutive number of digits NOT starting with 0. For example if N=1021, it has 7 subnumbers, namely, 1, 10, 102, 1021, 2, 21 and 1 (again). Here is your task: please calculate the sum of all the subnumbers of N. For 1021, the sum is 1+10+102+1021+2+21+1 = 1158. Since the result may be very large, output the answer modulo 1000000007 (109+7) please.
Input Specification:
Each input file contains one test case, which gives the integer N (0<N<10100000) in a line.
Output Specification:
Print in a line the sum of all N's subnumbers (modulo 1000000007).
Sample Input:
1234567890123456789
Sample Output:
332876913
題目大意:給出一個很大的數字字符串(可能有100000位),計算它的子數組字符串(非0開頭)的數字和的大小,注意結果對1000000007取模。
解題思路:
我用1024來舉例
1開頭:1,10,102,1024,可以發現結果和爲1*1111,0*111,2*11,4*1
0開頭:0,02,024,可以發現結果和爲0*111,2*11,4*1(不過這個不合要求)
2開頭:2,24,可以發現結果和爲2*11,4*1
4開頭:4,可以發現結果和爲4*1
總結規律,先不考慮0的問題,,設字符串的總長度爲L,位於第i位的數字num(從左往右數,從0開始計數),對結果的貢獻爲 num * (i+1)* 1...1(L-i個1),但是本題並沒有將每個數字單獨分開看,因爲如果出現0,則其後的數字計算的次數都要受影響。也就是並一定出現i+1次。
考慮設一個tempans,記錄目前遍歷到的數字
tempans = 4 , ans = 4
tampans=24, ans = 4+24
tempans = 024, ans=4+24
tempans = 1024, ans= 4+24+1024
代碼:
#include <bits/stdc++.h>
using namespace std;
long long int mod = 1000000007;
int main(){
string s;
cin >> s;
reverse(s.begin(), s.end());
int len = s.length();
long long int ans = 0, tempans = 0;
vector<long long int> v(len);
v[0] = 1;
for(int i = 1; i < len; ++ i)
v[i] = (v[i-1] * 10 + 1) % mod;
for(int i = 0; i < len; ++ i){
tempans += (s[i] - '0') * v[i];
if(s[i] != '0')
ans = (ans + tempans) % mod;
}
printf("%lld", ans);
}