Acwing 105 - 七夕祭【环形纸牌均分问题】
- 环形纸牌均分问题 的详细思路:AcWing 105. 七夕祭
AC代码:
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 1e5 + 10;
LL row[N], col[N], n, m, t;
LL s[N], c[N];
LL get(LL * a, LL n)
{
for(int i=1; i<=n; i++) s[i] = s[i - 1] + a[i];
if(s[n] % n) return -1;
LL avg = s[n] / n;
c[1] = 0;
for(int i=2; i<=n; i++) c[i] = 1ll * (i - 1) * avg - s[i - 1];
sort(c + 1, c + 1 + n);
LL res = 0;
for(int i=1; i<=n; i++) res += llabs(c[(n + 1) / 2] - c[i]);
return res;
}
int main()
{
cin >> n >> m >> t;
while(t -- ){
int x, y; cin >> x >> y;
row[x] ++, col[y] ++ ;
}
LL sr = get(row, n);
LL sc = get(col, m);
if(sr == -1 && sc == -1) cout << "impossible";
else if(sr == -1) cout << "column " << sc;
else if(sc == -1) cout << "row " << sr;
else cout << "both " << sc + sr;
system("pause");
return 0;
}
一道杂题
Acwing 107 - 超快速排序
题意:求最少相邻元素交换次数使得序列升序。
思路:最少交换次数=逆序对个数。
证明:当序列非非严格递增时,一定存在两个相邻的数有 a i − 1 > a i a_{i-1}>a_i ai−1>ai,我们就可以交换这两个数。