AcWing第58场周赛
第一题:4488. 寻找1 - AcWing题库
思路:直接遍历一遍就OK了
代码
#include <bits/stdc++.h>
using namespace std;
const int N = 110;
int a[N];
int n;
int main()
{
ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
cin >> n;
int st = 0;
for(int i = 0; i < n; i ++) cin >> a[i];
for(int i = 0; i < n; i ++)
{
if(a[i]) st = 1;
}
if(st) cout << "YES" << endl;
else cout << "NO" << endl;
return 0;
}
思路:用一个数组f:f[i] 表示最后一个数为a[i]的长度,初始化时所有的值都为1, 如果i >= 1, a[i- 1] * 2 >= a[i] f[i] = f[i - 1] + 1;遍历一遍f找到最大值即可。
代码
#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 10;
int a[N];
int n;
int f[N];
int main()
{
ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
cin >> n;
for(int i = 0; i < n; i ++) cin >> a[i];
for(int i = 0; i < n; i++) f[i] = 1;
for(int i = 1; i < n; i ++)
{
if(a[i - 1] * 2 >= a[i])
f[i] = f[i - 1] + 1;
}
int ans = 1;
for(int i = 0; i < n; i ++) {
ans = max(ans, f[i]);
}
cout << ans << endl;
return 0;
}
思路:根据题目意思,染色的话就是将一个子树的节点的全部为一个颜色,这个就可以直接遍历一遍,如果该节点的颜色和该节点的父节点的颜色不一样,那么染色的次数就应该+1.
代码
#include <bits/stdc++.h>
using namespace std;
const int N = 1e4 + 10;
int p[N];
int c[N];
int n;
int main()
{
ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
cin >> n;
for(int i = 2; i <= n; i ++) cin >> p[i];
for(int i = 1; i <= n; i ++) cin >> c[i];
int ans = 1;
for(int i = 2; i <= n; i ++)
{
if(c[i] != c[p[i]]) ans ++;
}
cout << ans;
return 0;
}
力扣第300场周赛
思路:用一个哈希表来存储每个字母出现的顺序,最后遍历一遍即可
代码
class Solution {
public:
string decodeMessage(string key, string message) {
unordered_map<char, int> mp;
int cnt = 1;
for(auto i : key)
{
if(i >= 'a' && i <= 'z')
if(!mp.count(i))
mp[i] = cnt ++;
}
for(auto &i : message)
{
if(i >= 'a' && i <= 'z')
i = mp[i] + 'a' - 1;
//s.push_back(mp[i] + 'a');
}
return message;
}
};
第二场:2326. 螺旋矩阵 IV - 力扣(LeetCode)
思路:模拟。
代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
vector<vector<int>> spiralMatrix(int m, int n, ListNode* head) {
vector<vector<int>> ans(m, vector<int>(n, -1));
auto p = head;
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
int f = 1;
int x = 0, y = 0;
while(p != NULL)
{
ans[x][y] = p->val;
if(x + dx[f] < 0 || y + dy[f] < 0 || x + dx[f] >= m || y + dy[f] >= n || ans[x + dx[f]][y + dy[f]] != -1) f = (f + 1) % 4;
x += dx[f], y += dy[f];
p = p->next;
}
return ans;
}
};