1、均分纸牌
题意概括:
解题思路:可以分类讨论,先讨论1,n的情况,再从讨论[2,n-1]的情况。也可以直接遍历[1,n],如果a[i] != avg,那么a[i+1] += (a[i]-avg),ans++,对于这个式子的理解,如果a[i] > avg,那么需要向右传递,a[i] - avg为正数,反之需要向后一个索取,a[i]-avg为负数,达到了同时兼顾左边和右边,并且对于1和N,仅有一种情况。
代码:
#include <iostream>
using namespace std;
const int N = 110;
int a[N];
int n , total;
int ans;
int main()
{
cin >> n;
for(int i = 1 ; i <= n ; i++) cin >> a[i] , total += a[i];
int avg = total / n;
for(int i = 1 ; i <= n ; i++)
if(a[i] != avg) a[i + 1] += a[i] - avg , ans++;
cout << ans << endl;
return 0;
}
2、糖果传递
题意概括:一个数组组成一个环,每次每个值可以向左右两边传递一个值,求最小次数。
解题思路:
代码:
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long LL;
const int N = 1e6+10;
LL a[N];
int n;
LL s[N],c[N];
int main()
{
cin >> n;
LL sum = 0;
for (int i = 1; i <= n; i ++ )
{
cin >> a[i];
sum += a[i];
s[i] = s[i-1] + a[i];
}
LL avg = sum/n;
for (int i = 1; i <= n; i ++ )
{
c[i] = s[i-1] - (i-1) * avg;
}
sort(c+1,c+1+n);
LL ans = 0;
for (int i = 1; i <= n; i ++ )
{
ans += abs(c[i] - c[n/2+1]);
}
cout << ans << endl;
return 0;
}
3、七夕祭
题意概括:本题在上一题的基础上增加了判断行列两种情况即可
代码:
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long LL;
const int N = 100010;
int n,m,t;
int row[N],col[N];
LL s[N],c[N];
LL work(int n,int a[])
{
LL sum = 0;
for (int i = 1; i <= n; i ++ )
{
sum += a[i];
s[i] = s[i-1] + a[i];
}
if(sum % n != 0) return -1;
LL avg = sum / n;
for (int i = 1; i <= n; i ++ )
{
c[i] = s[i-1] - (i-1)*avg;
}
sort(c+1,c+1+n);
LL res = 0;
for (int i = 1; i <= n; i ++ )
{
res += abs(c[i] - c[n/2+1]);
}
return res;
}
int main()
{
cin >> n >> m >> t;
while(t --)
{
int x,y;
cin >> x >> y;
row[x]++,col[y]++;
}
LL r = work(n,row);
LL c = work(m,col);
if(r != -1 && c != -1) cout << "both" << " " << r+c << endl;
else if(r != -1) cout << "row" << " " << r << endl;
else if(c != -1) cout << "column" << " " << c << endl;
else cout << "impossible" << endl;
return 0;
}