Algorithm UVa Live 6823算法

Algorithm UVa Live 6823算法,algorithm,Algorithm,下面的代码是如何解决这个问题的? 我只想解释一下代码中使用的算法。 提前谢谢 #include <bits/stdc++.h> using namespace std; int main() { string st; while(cin>> st){ long long int cnt=0,x=0,arr[]={1,0,0}; for(int a=0;a<st.length();a++){ if

下面的代码是如何解决这个问题的? 我只想解释一下代码中使用的算法。 提前谢谢

#include <bits/stdc++.h>
using namespace std;
int main()
{
    string st;
    while(cin>> st){
        long long int cnt=0,x=0,arr[]={1,0,0};
        for(int a=0;a<st.length();a++){
            if(!isdigit(st[a])){
                x=0;
                arr[0]=1;
                arr[1]=arr[2]=0;
            }
            else{
                x=(x+st[a]-48)%3;
                cnt+=arr[x];
                arr[x]++;
            }
        }
        cout<< cnt <<endl;
    }
    return 0;
}
#包括
使用名称空间std;
int main()
{
字符串st;
而(cin>>st){
long-long-int-cnt=0,x=0,arr[]={1,0,0};

对于(int a=0;a,该算法利用规则,即,如果一个数字的数字之和可被3整除,则该数字可被3整除。它跟踪数字之和的剩余部分被3整除的出现频率(例如,0、1或2)。每当添加新数字时,具有相同余数的子字符串将添加另一个可被3整除的置换子字符串。注意:使用的常量
48
'0'
的ASCII值

这可能是最好的例子。考虑字符串<代码> 12321代码/代码>,逐位处理。

// "iteration" #0 (st[a] = '')
x = 0
arr[] = {1,0,0}
cnt = 0
// iteration #1 (st[a]='1'). '1' is not divisible by three.
x = 1
arr[] = {1,1,0}
cnt   = 0
// iteration #2 (st[a]='2'). '12' is divisible by three.
x = 0
arr[] = {2,1,0}
cnt   = 1
// iteration #3 (st[a]='3'). '123' and '3' are divisible by three
x = 0
arr[] = {3,1,0}
cnt   = 3
// iteration #4 (st[a]='2'). No new divisible by three substrings
x = 2
arr[] = {3,1,1}
cnt   = 3
// iteration #5 (st[a]='1'). '12321', '321' and '21' are divisible by 3.
// note, the other times when x = 0, st[0..a] = '', '12', '123'
x = 0
arr[] = {4,1,1}
cnt   = 6
你可以继续添加数字,看看它是如何工作的。当它碰到一个非数字字符时,计数会重置,因为任何非数字字符都不能参与排列