HDOJ 5373 The shortest problem 【數論】

HDOJ 5373 The shortest problem 【數論】

題目鏈接 http://acm.hdu.edu.cn/showproblem.php?pid=5373


題目給一個初始數據和重複次數
每一次都在初始數據末端連接上現有數據的各個位的和
之後對最後得出的數據除以11,如果可以整除輸出Yes,否則輸出No


可以被11整除的數有一個特徵:
奇數位減去偶數位的數最後得出的數如果能被11整除,原數就可以被11整除,否則原數也不能被11整除
因此用sum保存之前的各個位之和,
遍歷t次之後將dif與11取模即可
注意使用之前的位數爲奇數或偶數,現在的位數爲奇數或偶數來判斷對最末尾的數是先加還是先減


提供隊友的法二:
以358÷11爲例:
這裏寫圖片描述
所以對於每次得出的結果直接對11取模即可。。。不過還是要保存原先的每位的和
保證下次加入末尾的數據依然正確
就素醬紫。。。


#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<vector>
#include<queue>
#include<set>
using namespace std;
#define clr(c) memset(c, 0, sizeof(c));
const int INF = 0x3f3f3f3f;
typedef long long LL;
int n, t, Case;
int dif, len;
int sum;
int flag, num;
int oddBefore, odd;
int ll;
void fun(int nn){
    int ll = 0;
    int difsub = 0;
    int difplus = 0;
    flag = 1;
    while(nn){
        num = nn % 10;
        difplus += flag*num;
        difsub += -1*flag*num;
        flag *= -1;
        sum += num;
        nn /= 10;
        ll++;
    }
    if(ll & 1) odd = true;
    else odd = false;
    if(odd == oddBefore){
        dif += difsub;
        oddBefore = false;
    }
    else{
        dif += difplus;
        oddBefore = true;
    }
}

int main(){
    Case = 1;
    while(~scanf("%d%d", &n, &t)){
        if(n == -1 && t == -1) break;
        printf("Case #%d: ", Case++);
        if(n == 0){
            puts("Yes");
            continue;
        }
        if(t == 0){
            if(n % 11) puts("No");
            else puts("Yes");
            continue;
        }
        flag = 1, num = 0, dif = 0, sum = 0, ll = 0;
        int tempN = n;
        int difplus = 0;
        int difsub = 0;
        while(tempN){
            num = tempN % 10;
            difplus += flag*num;
            difsub += -1*flag*num;
            flag *= -1;
            sum += num;
            tempN /= 10;
            ll++;
        }
        if(ll & 1){
            oddBefore = true;
            dif = difplus;
        }
        else{
            oddBefore = false;
            dif = difsub;
        }
        for(int i = 0; i < t; i++) fun(sum);
        if(dif % 11) puts("No");
        else puts("Yes");
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章