# Modular Arithmetic# String Manipulation

e963 - Error

🔗 前往 ZeroJudge 原題

題目描述

題目要求判斷給定的字串 s 是否滿足一個特定的模運算條件。具體來說,將字串中的每個字元視為一個數字,並根據其在字串中的位置計算一個加權和,然後判斷這個加權和是否能被 3 整除。權重是根據一個固定的數字 e (139%mod) 進行迭代計算的,其中 mod 是字串第一個字元模 3 的結果加 2。

解題思路

解題思路是根據題目描述,計算字串的加權和,並檢查其是否為 3 的倍數。

  1. 計算 modmod = s[0] % 3 + 2
  2. 計算 ee = 139 % mod
  3. 初始化 total = 0timee = 1
  4. 遍歷字串 s,對於每個字元 s[i]
    • (s[i] * timee) % mod 加到 total 上。
    • 更新 timee = (timee * e)
  5. 如果 total % mod 等於 0,則輸出 "yes",否則輸出 "no"。

複雜度分析

  • 時間複雜度: O(n),其中 n 是字串的長度。因為需要遍歷字串一次來計算加權和。
  • 空間複雜度: O(1),因為只使用了常數級別的額外空間。

程式碼

#include <iostream>
#include <string>
using namespace std;
typedef long long ll;
#define FOR(i, j, k, in) for (int i=j ; i<k ; i+=in)
#define RFOR(i, j, k, in) for (int i=j ; i>=k ; i-=in)
#define REP(i, j) FOR(i, 0, j, 1)
#define IOS() ios_base::sync_with_stdio(0);cin.tie(0)

/********** Good Luck :) **********/
int main(){
    IOS();
    int t;
    string s;
    cin >> t;
    while(t--){
        cin >> s;
        int sl=s.length();
        ll mod=s[0]%3+2,total=0,timee=1,e=139%mod;
        REP(i, sl){
            total+=(s[i]*timee)%mod;
            timee*=e;
        }
        (total%mod)?cout << "no" << '\n':cout << "yes" << '\n';
    }
    return 0;
}

Discussion