1. 程式人生 > >[A]1065 A+B and C (64bit)(挖坑待填)

[A]1065 A+B and C (64bit)(挖坑待填)

\n con 大於 64bit suppose rst tell art 問題

Given three integers A, B and C in [-2^63, 2^63], you are supposed to tell whether A+B > C.

Input Specification:

The first line of the input gives the positive number of test cases, T (<=10). Then T test cases follow, each consists of a single line containing three integers A, B and C, separated by single spaces.

Output Specification:

For each test case, output in one line “Case #X: true” if A+B>C, or “Case #X: false” otherwise, where X is the case number (starting from 1).”

Sample Input:

3
1 2 3
2 3 4
9223372036854775807 -9223372036854775808 0

Sample Output:

Case #1: false
Case #2: true
Case #3: false


這道題如果用大整數運算,不,今天不想寫了-.-

過幾天再來填坑。
先記錄另外一種解法(來自算法筆記):

  • 兩個正數相加溢出結果為 -
  • 兩個負數相加如果溢出結果為+

但是還有幾個小細節需要註意:
long long的範圍是[-2^63,2^63-1]

  • 如果A B的最大值均為2^63 -1 ,則A + B >= 2^64 - 2,正溢後的區間為 [-2^63,-2] ,-2是由 (2^64 - 2)% 2^64 = -2得到;
  • 如果A B的最大值均為-2^63 ,則A + B >= -2^64 ,負溢後的區間為 [0,2^63) ,0是由 (-2^64 )% 2^64 = 0得到;
    所以如果數據範圍是[-2^63,2^63-1],使用這種方法我覺得會比較合理一點。

最後還有一個問題,如果直接在if語句中判斷 a+b是否大於0,就不能完全通過測試點,但是如果先將a+b賦值給某個變量(如res)時,再判斷res是否大於0就可以通過。網上查了也沒有答案,至今未解。

code:
#include<cstdio>

int main(void){
    int n;
    long long a,b,c;
    scanf("%d",&n);
    for(int i = 1; i <= n; i++){
        scanf("%lld %lld %lld",&a,&b,&c);
        
        long long res = a + b;
        
        if(a > 0 && b > 0 && res < 0 ) {
            printf("Case #%d: true\n",i);
            continue;
        }
        if(a < 0 && b < 0 && res >= 0 ) {
            printf("Case #%d: false\n",i);
            continue;
        }

        if( a + b > c) 
            printf("Case #%d: true\n",i);
        else    printf("Case #%d: false\n",i);
    }
    
    return 0;
}

[A]1065 A+B and C (64bit)(挖坑待填)