編輯:關於 Android 程式設計
這題與 Div2 的最後一題很類似,唯一的差別是:Div2 那題要求兩數之差至多為 K,本題改成至少 K,難度因此上升一階,DP 的狀態也不好想。
沿用「只考慮尚未配對的數字」這個思路,但要把未配對的數字分成兩類:
然後從大到小依序處理 2N 個數字。狀態定義為 dp[n][g][s]:n 表示已處理到第幾個數字,g 是尚未配對的 good 數字個數,s 則用 bitmask 記錄 special 數字各自的偏移狀態(範圍在 0 到 K-1 之間,所以用 K 位元剛好夠)。
之所以要區分兩類,是因為新加入的數字 x 只能與「大於等於 x + K」的數字配對。若某個未配對數字已經離得夠遠(good),它就永遠有機會被後續配掉;而落在 (x, x+K) 區間內的 special 數字,其可用性會隨每次加入新數字而改變,必須用 bitmask 追蹤每個位置往前還差多少才達到 K。
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <stack>
#include <deque>
#include <queue>
#include <set>
#include <map>
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cmath>
#include <cstring>
using namespace std;
const int MOD = 1000000007;
const int MAX_N = 50;
const int MAX_K = 10;
int dp[2 * MAX_N + 1][2 * MAX_N + 1][1 << MAX_K];
class AlienAndSetDiv1 {
public:
int K;
int calc(int s, int g, int n) {
int res = 0;
if (-1 != dp[n][g][s]) {
return dp[n][g][s];
}
if (n == 0) {
if (0 == s && 0 == g) {
res = 1; // base case
}
} else {
if (0 == s && 0 == g) {
if (1 == K) {
res += 2 * calc(0, 1, n - 1); // add
} else {
res += 2 * calc(1, 0, n - 1); // add
}
res %= MOD;
} else if (0 == s && g != 0) {
res += calc(0, g - 1, n - 1); // match
if (1 == K) {
res += calc(0, g + 1, n - 1); // add
} else {
res += calc(1, g, n - 1); // add
}
res %= MOD;
} else if (s != 0 && 0 == g) {
// K != 1,只能 add
int newset = s;
int i = 0;
// 注意位運算的優先順序,括號必須加上
for (i = 0; (newset & 0x80000000) == 0; newset = (newset << 1), ++i) {
}
int mx = 31 - i; // s 不為 0 的最高位
if (n + mx + 1 - (n - 1) >= K) { // 會使 g 增加
int t = (s - (1 << mx)); // 清掉 mx 位
res += calc((t << 1) | 1, 1, n - 1); // add
res %= MOD;
} else {
res += calc((s << 1) | 1, 0, n - 1); // add
res %= MOD;
}
} else {
// s != 0 && g != 0,K != 1
int newset = s;
int i = 0;
for (i = 0; (newset & 0x80000000) == 0; newset = (newset << 1), ++i) {
}
int mx = 31 - i; // s 不為 0 的最高位
if (n + mx + 1 - (n - 1) >= K) { // 判斷是否使 g 變化
int t = (s - (1 << mx));
res += calc(t << 1, g, n - 1); // match
res += calc((t << 1) | 1, g + 1, n - 1); // add
} else {
res += calc(s << 1, g - 1, n - 1); // match
res += calc((s << 1) | 1, g, n - 1); // add
}
res %= MOD;
}
}
dp[n][g][s] = res;
return res;
}
int getNumber(int N, int K) {
this->K = K;
memset(dp, -1, sizeof(dp));
return calc(0, 0, 2 * N);
}
};
Volley 源碼深度分析:從請求創建到響應分發
我曾寫過一篇對 Volley 源碼分析得毫無頭緒的文章,回頭看時不甚滿意,於是刪掉重寫,便有了今天這篇。 Volley 的使用步驟 1. 創建一個 RequestQueu
Android 開發筆記:使用 XmlPullParser 解析 XML 資源文件
在 Android 開發中,XML 經常用於儲存設定、版面配置與靜態資料。除了常見的 DOM 與 SAX 解析方式之外,Android 官方也推薦使用輕量且事件驅動的 X
榮耀8與榮耀V8哪個好?從外型工藝、螢幕到價格全面比較
華為在上海的發表會上正式推出榮耀8。此前傳聞它比 V8 做工更精、顏值更高,看到實機之後大致可以確認這個說法。於是問題來了:想買榮耀的人,該選 8 還是 V8?華為榮耀8
PopupWindow 模擬 iOS 底部彈窗
底部彈窗的應用在行動應用中,底部彈窗常用於提供操作選單,例如選擇頭像來源、分享管道或取消操作。它比中央對話框更貼近拇指操作,也符合多數使用者的習慣。PopupWindow