货仓选址
中位数法
#include <iostream>
#include <math.h>
#include <algorithm>
using namespace std;
const int N=1e5+5;
int main()
{
int n;
cin>>n;
int a[N];
for(int i=0;i<n;i++)
{
cin>>a[i];
}
sort(a,a+n);
int res=0;
for(int i=0;i<n;i++)
res+=abs(a[i]-a[n>>1]);//这里改成i>>1也可以AC
cout<<res<<endl;
return 0;
}
红与黑
洪水灌溉、
//宽搜写法
#include <iostream>
#include <queue>
#include <algorithm>
#define x first
#define y second
using namespace std;
typedef pair<int, int> PII;
const int N = 25;
int n, m;
char g[N][N];
int bfs(int sx, int sy)
{
queue<PII> q;
q.push({sx, sy});
g[sx][sy] = '#';
int res = 0;
int dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1};
while (q.size())
{
auto t = q.front();
q.pop();
res ++ ;
for (int i = 0; i < 4; i ++ )
{
int x = t.x + dx[i], y = t.y + dy[i];
if (x < 0 || x >= n || y < 0 || y >= m || g[x][y] != '.') continue;
g[x][y] = '#';
q.push({x, y});
}
}
return res;
}
int main()
{
while (cin >> m >> n, n || m)
{
for (int i = 0; i < n; i ++ ) cin >> g[i];
int x, y;
for (int i = 0; i < n; i ++ )
for (int j = 0; j < m; j ++ )
if (g[i][j] == '@')
{
x = i;
y = j;
}
cout << bfs(x, y) << endl;
}
return 0;
}
//深搜写法
#include <iostream>
using namespace std;
const int N = 25;
int n, m;
char g[N][N];
int dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1};
int dfs(int x, int y)
{
int res = 1;
g[x][y] = '#';
for (int i = 0; i < 4; i ++ )
{
int a = x + dx[i], b = y + dy[i];
if (a >= 0 && a < n && b >= 0 && b < m && g[a][b] == '.')
res += dfs(a, b);
}
return res;
}
int main()
{
while (cin >> m >> n, n || m)
{
for (int i = 0; i < n; i ++ ) cin >> g[i];
int x, y;
for (int i = 0; i < n; i ++ )
for (int j = 0; j < m; j ++ )
if (g[i][j] == '@')
{
x = i;
y = j;
}
cout << dfs(x, y) << endl;
}
return 0;
}
回文平方
考点:
1.十进制转化成其他进制:短除法
2.其他进制转化成十进制:秦九韶算法
3.其他进制转化成其他进制
(1) 用十进制过渡
(2) 短除法
4.双指针法判断是否是回文数
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
char get(int x)
{
if(x <= 9) return x +'0';
return x-10+'A';
}
string change(int n,int b)
{
string num;
while(n) num+=get(n % b),n/=b;
reverse(num.begin(),num.end());
return num;
}
bool check(string num)
{
for(int i=0,j=num.size() - 1;i<j;i++,j--)
{
if(num[i]!=num[j])return false;
}
return true;
}
int main()
{
int b;
cin>>b;
for(int i=1;i<=300;i++)
{
auto ans=change(i*i,b);
if(check(ans))
{
cout<<change(i,b)<<' '<<ans<<endl;
}
}
return 0;
}
寒假第一周每日一题打卡,希望这个寒假可以不负众望