SPOJ 1881 Instruction Decoder

Description

Mathews uses a brand new 16-bit instruction processor. (Yeah i am being sarcastic!). It has one register (say R) and it supports two instructions:

  • ADD X; Impact: R = (R + X) mod 65536
  • MUL X; Impact: R = (R * X) mod 65536
  • [For both instructions 0 <= X <= 65535]
Mathews sees a segment of code, but doesnot know what value the register had before the code was being executed. How many possible values can the register have after the segment completed execution?
Input Format:
The input file consists of multiple testcases.
The first line of each testcase contains one integer, N. (1 <= N <= 100,000).
The following N lines contain one instructions each.
Input terminates with a line containing N=0, which must not be processed.

Output Format:
For each testcase print one integer in a single line, denoting the number of different values the register can take after code execution.

Sample Input:
1
ADD 3
1
MUL 0
5
MUL 3
ADD 4
MUL 5
ADD 3
MUL 2
8
ADD 32
MUL 5312
ADD 7
MUL 7
ADD 32
MUL 5312
ADD 7
MUL 7
0
Sample Output:
65536
1
32768
16

看第一眼題的時候覺得這題肯定不難,於是果斷開題,結果讀題愣是讀了20分鐘,還沒有看懂題意~(默默表示被百度翻譯坑了一發)
後來冷靜想了一下,發現ADD操作可以直接忽略,只需要把MUL的數因數分解就可以了。
當然,這題數據貌似卡的不嚴,暴力打表也可以做出來。

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;

int main()
{
    int n;
    while(~scanf("%d",&n) && n)
    {
        int temp;
        char op[10];
        int cnt = 65536;
        bool flag = true;
        for(int i=0; i<n; i++)
        {
            scanf("%s %d",op,&temp);
            if(op == "MUL")
            {
                if(temp == 0)
                {
                    flag = false;
                    break;
                }
                while(temp % 2 == 0)
                {
                    cnt >>= 1;
                    temp /= 2;
                }
            }
        }
        if(!flag || !cnt)
            printf("1\n");
        else
            printf("%d\n",cnt);

    }
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章