题目——异或和之和,给定一个数组Ai,分别求其每个字段的异或和,并求出它们的和。
一开始看不懂题目是何意思,后来一番苦查,在csdn上找到一篇文章是解释这道题目的。步骤是先按照位全部对应求一次异或,然后按照位两两异或求和。两两异或呢,可以先统计该位上的0和1分别多少个,然后个数相乘再乘该位的权重,求和就可以了。
#include<iostream>
#include<algorithm>
#include<unordered_map>
#include<map>
using namespace std;
typedef long long ll;
const int N = 100010;
int n;
int a[N][25];
int cnt[N][25];
int main()
{
cin >> n;
for (int i = 1; i <=n; i++)
{
int x;
cin >> x;
for (int j = 0; j <= 20; j++)
{
a[i][j] = (x >> j) & 1; //x第j位赋给a[i][j]
a[i][j] ^= a[i - 1][j]; //异或
cnt[j][a[i][j]]++; //统计该位0和1分别多少个
}
}
long long ans = 0;
for (int j = 0; j <= 20; j++)
{
cnt[j][0]++;
ans += 1LL * (1 << j)*cnt[j][0]*cnt[j][1];
}
cout << ans << '\n';
return 0;
}
像素放置问题,有点像扫雷。主要是通过递归挨个试,再次摘抄官网题解代码。
#include<iostream>
#include<string>
using namespace std;
int n;
int m;
const int maxn = 15;
char a[maxn][maxn];
int mp[maxn][maxn];
int ans[maxn][maxn];
int flag;
int count(int x, int y)//统计九宫格内黑块数目
{
return ans[x - 1][y - 1] + ans[x][y - 1] + ans[x + 1][y - 1] + ans[x - 1][y] + ans[x][y] + ans[x + 1][y] + ans[x - 1][y + 1] + ans[x][y + 1] + ans[x + 1][y + 1];
}
bool check() //判断该九宫格内的黑块数目是否等于该格的数字大小
{
int i, j;
for (i = 1; i <= n; i++)
{
for (j = 1; j <= m; j++)
{
if (mp[i][j] == -1)
continue;
else if (count(i, j) != mp[i][j])
return false;
}
}
return true;
}
bool check2(int x, int y) //判断除自己外的所有格是否符合要求
{
int i, j;
for (i = 1; i <= x - 2; i++)
{
for (j = 1; j <= m; j++)
{
if (mp[i][j] == -1)
continue;
else if (count(i, j) != mp[i][j])
return false;
}
}
if (x >= 2)
{
for (j = 1; j <= y - 2; j++)
{
if (mp[x - 1][j] == -1)
continue;
else if (count(x - 1, j) != mp[x - 1][j])
return false;
}
}
return true;
}
void dfs(int x, int y)
{
if (flag)
return;
if (x == n + 1) //所有行都遍历完
{
if (check())
{
flag = 1;
int i, j;
for (i = 1; i <= n; i++)
{
for (j = 1; j <= m; j++)
cout << ans[i][j];
cout << endl;
}
}
return;
}
if (!check2(x, y))
return;
//将每格一次换成黑格白格试验
ans[x][y] = 1;
if (y == m) //到达一行的末尾
dfs(x + 1, 1);
else
dfs(x, y + 1);
ans[x][y] = 0;
if (y == m)
dfs(x + 1, 1);
else
dfs(x, y + 1);
}
int main()
{
cin >>n>>m;
for(int i=1;i<=n;i++)
{
for (int j = 1; j <= m; j++)
{
cin >> a[i][j];
if (a[i][j] == '_')
mp[i][j] = -1;
else
mp[i][j] = a[i][j] - '0';
}
}
dfs(1, 1);
return 0;
}
下线过年时间有些长了哈哈哈哈哈