第一题
题目
思路
模拟 : 坐标转换
代码
#include <iostream>
using namespace std;
int arr[15][15];
int res[15][15];
int n, m;
int main()
{
cin >> n >> m;
for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= m; j++)
{
cin >> arr[i][j];
res[j][i] = arr[i][j];
}
}
for(int i = 1; i <= m; i++)
{
for(int j = 1;j <= n; j++)
{
cout << res[i][j] << " ";
}
cout << endl;
}
return 0;
}
// 64 位输出请用 printf("%lld")
第二题
题目
思路
DFS 枚举12个位置可能得4个选项
注意剪支:
- 判断当前选项是否还有剩余;
- 判断当前选项是否和前方选项相同;
代码
#include <iostream>
#include <vector>
using namespace std;
int arr[6];
bool same[13][13]; // i, j 的答案相同
int res;
vector<int> path; // 记录路径⾥⾯选了哪些选项
bool isSame(int pos, int cur)// pos 位置填 cur ,是否符合要求
{
for(int i = 1; i < pos; i++)
{
if(same[pos][i] && path[i] != cur) return false;
}
return true;
}
void dfs(int pos)
{
if(pos > 12)
{
res++;
return ;
}
for(int i = 1; i <= 4; i++)
{
if(arr[i] == 0) continue; // 选项已经用完了
if(!isSame(pos, i)) continue;
arr[i]--;
path.push_back(i);
dfs(pos + 1);
path.pop_back();
arr[i]++;
}
}
int main()
{
for(int i = 1; i <= 5; i++) cin >> arr[i];
int t = arr[5];
while(t--)
{
int x, y;
cin >> x >> y;
same[x][y] = same[y][x] = true;
}
path.push_back(0); // 填 0 位置(类似于占位符)
dfs(1);
cout << res <<endl;
return 0;
}
第三题
题目
思路
利用两个数组,来统计,当前位置左右的最高柱子;
则当前位置能容纳的水的数量,等于 当前位置左右最高柱子的最小值间当前位置
代码
class Solution {
public:
int trap(vector<int>& height) {
int n = height.size();
vector<int> left(n);
auto right = left;
left[0] = height[0];
for(int i = 1; i < n; i++)
{
left[i] = max(left[i - 1], height[i]);
}
right[n - 1] = height[n - 1];
for(int i = n - 2; i >= 0; i--)
{
right[i] = max(right[i + 1], height[i]);
}
int res = 0;
for(int i = 0; i < n; i++)
{
res += min(left[i], right[i]) - (height[i]);
}
return res;
}
};