思路:
枚舉,我們讓出現先連續左括號和出現右括號的數量一一對應,我們從連續出現n個左括號開始枚舉,下一次枚舉是先連續出現n-1個左括號,在下一次是n-2……直到最后只能先有1個左括號為止,我們可以記錄一個變量cnt,來記錄當前的枚舉,枚舉一種情況后cnt++,即前半部分先枚舉了n-cnt,然后再枚舉cnt種
舉個例子,當n為4時,所有情況為:
cnt = 0,-> (((())))
cnt = 1, -> ((()))()
cnt = 2, -> (())(())
cnt = 3, -> ()((()))
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <vector> #include <cmath> using namespace std; typedef pair<int, int>PII; typedef long long LL; const int N = 100010; int a[N]; int main() { int T; cin >> T; while (T--) { int n; cin >> n; int cnt = 0; for (int j = 1; j <= n; j++) { string res; for (int i = 1; i <= n - cnt; i++) res += "("; for (int i = 1; i <= n - cnt; i++) res += ")"; for (int i = 1; i <= cnt; i++) res += "("; for (int i = 1; i <= cnt; i++) res += ")"; cnt++; cout << res << endl; } } return 0; }
思路:
思維題,因為這題要我們判斷,是否有正好m對,我們先算出cnt1最多可以組成多少對,再算出cnt2最少可以組成多少對,當m介於兩者之間時,一定存在正好m對的情況,否則一定不存在
而由於三種字符最多可以組成的對數各為a - 1,b - 1, c - 1對,所以cnt1 = a + b + c - 3
最少的情況我們這么考慮,假設A的數量最多,而本來A可以組成a - 1對,而當我們在每兩個A間都插入一個B或一個C后,對子數就變為最少,變為a - 1 - b - c對,當然這個答案可能是負的,但是當答案是負的的情況表示可以一個對子都沒有,那么這種情況我們把cnt2置為0,表示有0個對子就好了。當然,這只是A最多的情況,當B最多或者C最多的情況同理,只要判斷一下誰最多就好了。
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <vector> #include <cmath> using namespace std; typedef pair<int, int>PII; typedef long long LL; const int N = 100010; int a[N]; int main() { int T; cin >> T; while (T--) { int a, b, c, m; cin >> a >> b >> c >> m; int cnt1 = 0; cnt1 += a + b + c - 3;//最多可以組成的對子數 int cnt2 = 0;//最少對子數 if(a >= b && a >= c) cnt2 += a - b - c - 1; else if(b >= a && b >= c) cnt2 += b - a - c - 1; else if(c >= a && c >= b) cnt2 += c - b - a - 1; if (cnt2 < 0) cnt2 = 0; if (cnt2 <= m && cnt1 >= m) cout << "YES" << endl; else cout << "NO" << endl; } return 0; } //1 8 1 0 //abacaaaaaa //3 2 1 0 //ababac //3 2 1 1 //abbaca
思路:
用lower_bound,
卡cin
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <vector> #include <cmath> using namespace std; typedef pair<int, int>PII; typedef long long LL; const int N = 200010; int n, m; LL a[N]; LL x, y; LL sum; int main() { ios::sync_with_stdio(false); cin.tie(0); cin >> n; for (int i = 1; i <= n; i++) cin >> a[i], sum += a[i]; sort(a + 1, a + n + 1); cin >> m; while (m--) { cin >> x >> y; int idx = lower_bound(a + 1, a + n + 1, x) - a; LL res = 1e18, minx = 0, maxx = 0; if (idx == n + 1)//如果找到了末尾,那么肯定是選最后的更優 { idx--; res = x - a[n]; if (y - (sum - a[n]) > 0) res += y - (sum - a[n]); } else//選擇idx的位置 { LL tmp = 0; if (x > a[idx]) tmp += x - a[idx]; if (y - (sum - a[idx]) > 0) tmp += y - (sum - a[idx]); res = min(res, tmp); tmp = 0; idx--; if (idx != 0) { if (x > a[idx]) tmp += x - a[idx]; if (y - (sum - a[idx]) > 0) tmp += y - (sum - a[idx]); res = min(res, tmp); } } cout << res << endl; } return 0; }
真是個悲傷的故事。。。