会发现最后每堆纸牌的数量为其总和的平均数,故只要这堆纸牌不是这个数字就注定需要挪动,由于只能与相邻的纸牌交换位置,那就直接与后一个纸牌进行交换操作,即使为负数也无关紧要,因为后一个纸牌也可以与它后面的进行交换。
#include
using namespace std;
const int N = 1e5 + 10;
int n, a[N], avg, sum, ans;
int main()
{
cin >> n;
for(int i = 1; i <= n; i ++)
{
cin >> a[i];
sum += a[i];
}
avg = sum / n;
for(int i = 1; i <= n; i ++)
{
if(a[i] < avg)
{
a[i + 1] -= avg - a[i];
ans ++;
}
if(a[i] > avg)
{
a[i + 1] += a[i] - avg;
ans ++;
}
}
cout << ans;
return 0;
}
dfs函数有三个参数,分别是 start(当前所选数字的下标,以防不断重复选这几个数),u(已经选了多少个数字),sum(所选数字的和)
#include
using namespace std;
const int N = 2e5 + 10;
int n, k, sum, ans, flag, a[N];
bool s[N];
void dfs(int start, int u,int sum)
{
if(u == k + 1)
{
flag = 0;
for(int i = 2; i <= sum / i; i ++)
{
if(sum % i == 0)flag = 1;
}
if(flag == 0)ans ++;
}
for(int i = start; i <= n; i ++)
{
dfs(i + 1, u + 1, sum + a[i]);
}
}
int main()
{
cin >> n >> k;
for(int i = 1; i <= n; i ++)
{
cin >> a[i];
}
dfs(1, 1, 0);
cout << ans;
return 0;
}
01背包
#include
using namespace std;
const int N = 3e5 + 10;
int n, m, v[N], w[N], dp[30][N];
int main()
{
cin >> n >> m;
for(int i = 1; i <= m; i ++)
{
cin >> v[i] >> w[i];
}
for(int i = 1; i <= m; i ++)
{
for(int j = 0; j <= n; j ++)
{
if(v[i] > j)dp[i][j] = dp[i - 1][j];
else dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - v[i]] + v[i] * w[i]);
}
}
cout << dp[m][n];
return 0;
}
一维优化写法
#include
using namespace std;
const int N = 3e5 + 10;
int n, m, v[N], w[N], dp[N];
int main()
{
cin >> n >> m;
for(int i = 1; i <= m; i ++)
{
cin >> v[i] >> w[i];
}
for(int i = 1; i <= m; i ++)
{
for(int j = n; j >= v[i]; j --)
{
dp[j] = max(dp[j], dp[j - v[i]] + v[i] * w[i]);
}
}
cout << dp[n];
return 0;
}
法一:
#include
using namespace std;
long long n, cnt, num, ans, b[1010], a[1010];
int main()
{
cin >> n;
while(n)
{
a[++ cnt] = n & 1;
n >>= 1;
}
for(int i = cnt + 1; i <= 32; i ++)
{
a[i] = 0;
}
reverse(a + 1, a + 1 + 32);
for(int i = 17; i <= 32; i ++)
{
b[++num] = a[i];
}
for(int i = 1; i <= 16; i ++)
{
b[++ num] = a[i];
}
long long k = 1;
for(int i = 32; i >= 1; i --)
{
ans += b[i] * k;
k *= 2;
}
cout << ans;
return 0;
}
法二:
#include
using namespace std;
int main()
{
unsigned int n;
cin >> n;
cout << ((n << 16) | (n >> 16));
return 0;
}
数组会炸!!!
#include
using namespace std;
const int N = 1e5 + 10;
long long n, a[N];
map mp;
int main()
{
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
cin >> n;
for(int i = 1; i <= n; i ++)
{
cin >> a[i];
mp[a[i]] ++;
}
for(auto i : mp)
{
cout << i.first << ' ' << i.second << '\n';
}
return 0;
}