算法競賽進階指南-位運算

很久沒更新簡書了,今日回歸,要是還有小伙伴能看見,請監(jiān)督我,我越來越菜了QAQ!

  1. a^b
    題目鏈接https://ac.nowcoder.com/acm/contest/996/A
    快速冪裸題。
#include<iostream>
using namespace std;

int main() {
    long long a, b, p;
    cin>>a>>b>>p;
    long long res = 1 % p;
    a %= p;
    while(b) {
        if(b & 1) res = (res * a) % p;
        a = (a * a)%p;
        b >>= 1;
    }
    cout<< res<<endl;
    return 0;
}
  1. 64位整數(shù)乘法
    題目鏈接https://ac.nowcoder.com/acm/contest/996/C
    快速冪變形。
#include<iostream>
using namespace std;

int main() {
    long long a,b,p;
    cin>>a>>b>>p;
    long long res = 0 % p;
    while(b) {
        if(b & 1) res = (res + a) % p;
        a = (a%p + a%p) % p;
        b >>= 1;
    }
    cout<<res<<endl;
    return 0;
}
  1. 最短Hamilton距離
    題目鏈接https://ac.nowcoder.com/acm/contest/996/D
    狀壓dp
    dp[1<<20][N]
    其中第一維代表的是狀態(tài),哪些點已經(jīng)遍歷過,每一位的0或者1代表當前點是否被遍歷。
    第二維代表當前遍歷過程中,走到了哪個點。
    dp狀態(tài)轉(zhuǎn)移公式:
    dp[state][j] = dp[state_k][k] + weight[k][j] , state_k = state 除掉j之后的集合,其中 state_k要包含k。
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;

const int N = 20,M = 1 <<20;
int n;
int dp[M][N],weight[N][N];

int main() {
    cin >> n;
    for(int i = 0; i < n; i++) {
        for(int j = 0;j < n;j++) {
            cin>>weight[i][j];
        }
    }
    memset(dp,0x3f,sizeof dp);
    dp[1][0] = 0;
    for(int i = 0;i < 1<<n;i++) {
        for(int j = 0; j < n; j++) {
            if(i >> j & 1) { // 判斷當前狀態(tài)是否可以停在j點
                for(int k = 0; k < n;k++) {
                    if((i - (1<<j)) >> k & 1) { // 判斷當前狀態(tài)去除j之后,是否包含k
                        dp[i][j] = min(dp[i][j], dp[i-(1<<j)][k] + weight[k][j]);
                    }
                }
            }
        }
    }
    cout<<dp[(1<<n) - 1][n-1]<<endl;
    return 0;
}

  1. lowbit實現(xiàn)
int lowbit1(int n) {
     return (~n + 1) & n;
}

int lowbit2(int n) {
     return (-n) & n;
}
最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內(nèi)容