PTA甲级
1134 Vertex Cover
#include<iostream>
#include<vector>
#include<set>using namespace std;typedef pair<int , int> PII;
vector<PII>v;
int n , m;bool check(set<int>&se)
{for(auto i : v)if(!se.count(i.first) && !se.count(i.second)) return false;return true;
}int main()
{cin >> n >> m;while(m --){int a , b;cin >> a >> b;v.push_back({a , b});}cin >> m;while(m --){int k;set<int>se;cin >> k;for(int i = 0;i < k;i ++){int x;cin >> x;se.insert(x);}if(check(se)) puts("Yes");else puts("No");}return 0;
}
1171 Replacement Selection
小顶堆
#include<iostream>
#include<algorithm>
#include<queue>
#include<vector>using namespace std;const int N = 1e5 + 10;
int n , m , cnt = 0;
int a[N];
priority_queue<int , vector<int> , greater<int>>q1 , q2;int main()
{cin >> n >> m;for(int i = 0;i < n;i ++) cin >> a[i];for(int i = 0;i < m;i ++) q1.push(a[i]);int idx = m;while(!q1.empty()){int t = q1.top();q1.pop();cout << t;if(idx < n) // 防止越界{if(t > a[idx]) q2.push(a[idx ++]);else q1.push(a[idx ++]);}if(q1.empty()) // 当前队列已经结束{swap(q1 , q2);cout << endl;}else cout << " ";// 继续输出}return 0;
}
1173 How Many Ways to Buy a Piece of Land
#include<iostream>using namespace std;const int N = 1e4 + 10;
typedef long long ll;
int n , cnt;
ll m , a[N];
bool st[N];void dfs(int u , ll total , ll&res)
{if(u == n) return ;if(total >= a[u]) res ++ , dfs(u + 1 , total - a[u] , res);
}int main()
{scanf("%d %lld" , &n ,&m);for(int i = 0;i < n;i ++){ll x;scanf("%lld" ,&x);if(x <= m) a[cnt ++] = x;}n = cnt;ll res = 0;for(int i = 0;i < n;i ++)dfs(i , m , res);printf("%lld" , res);return 0;
}
1135 Is It A Red-Black Tree
注意数组开大一点,否则段错误
#include<iostream>
#include<algorithm>
#include<vector>
#include<cstring>
#include<unordered_map>using namespace std;const int N = 100000 , INF = 0x3f3f3f3f;
int t , n;
int pre[N] , in[N] , abs_pre[N];
int l[N] , r[N];
unordered_map<int , int>idx;
bool f = true;int build(int pl , int pr , int il , int ir)
{int root = pre[pl];int k = idx[abs(root)];if(il < k) l[abs(root)] = build(pl + 1 , k - il + pl , il , k - 1);if(ir > k) r[abs(root)] = build(k - il + pl + 1 , pr , k + 1 , ir);bool fa = (root < 0 && l[abs(root)] > 0 && r[abs(root)] > 0);if(root < 0 && !fa) f = false;return root;
}
vector<int>black;
void dfs(int u , int total)
{int root = abs(u);if(root == INF || u > 0) total ++;if(root == INF) {black.push_back(total);return ;}dfs(l[root] , total);dfs(r[root] , total);
}int main()
{cin >> t;while(t --){memset(pre , 0 , sizeof pre) , memset(in , 0 , sizeof in);memset(l , 0x3f , sizeof l) , memset(r , 0x3f , sizeof r);cin >> n;for(int i = 0;i < n;i ++) cin >> pre[i] , in[i] = abs(pre[i]);sort(in , in + n);for(int i = 0;i < n;i ++) idx[in[i]] = i;if(pre[0] < 0) {f = true;puts("No");continue;}int root = build(0 , n - 1 , 0 , n - 1);dfs(root , 1);for(int i = 0;i < black.size();i ++)if(black[i] != black[0]) f = false;if(f) puts("Yes");else puts("No");f = true , idx.clear() , black.clear();}
}