Element Swapping(题目链接)
思路:
对于题目要求的序列a:
a1+2*a2+...+k*ak = Xa;a1^2+2*a2^2+...+k*ak^2 = Ya
输入的序列b:
b1+2*b2+...+k*bk = Xb;b1^2+2*b2^2+...+k*bk^2 = Yb
假设交换下标为l, r,对应bl, br
①Xb-Xa = (br-bl)*(r-l)
②Yb-Ya = (br-bl)*(r-l)*(r+l)
==>Yb-Ya = (Xb-Xa)*(l+r)
==>l+r = (Yb-Ya) /(Xb-Xa)
枚举l就能推出r和br,判断是否符合,复杂度O(n),不过有很多坑(除0和下标区间)
代码:
#include <bits/stdc++.h>
using namespace std;
#define ll long long
ll a[100005];
map<ll, ll> Map;
int main()
{
int t;
scanf("%d", &t);
while(t--)
{
Map.clear();
int n;
ll xa, ya;
scanf("%d %lld %lld", &n, &xa, &ya);
ll xb, yb;
xb = yb = 0;
for(int i=1; i<=n; i++)
{
scanf("%lld", &a[i]);
Map[a[i]]++;
yb += 1LL*i*a[i]*a[i];
xb += 1LL*i*a[i];
}
if(xb == xa)
{
if(yb != ya)
{
// 必定不存在
printf("0\n");
continue;
}
else
{
// 都相同时,只要交换相同元素就行
ll ans = 0;
map<ll, ll> ::iterator it;
for(it=Map.begin(); it!=Map.end(); it++)
ans += (it->second)*(it->second-1)/2;
printf("%lld\n", ans);
continue;
}
}
if((yb-ya)%(xb-xa))
{
printf("0\n");
continue;
}
ll mid = (yb-ya)/(xb-xa);
int cnt = 0;
for(int i=1; i<=n; i++)
{
ll bl = a[i];
ll br = mid-a[i];
// 防止除零
if(bl == br)
continue;
// 满足下标为整数
if((xb-xa)%(br-bl))
continue;
int r = i+(xb-xa)/(br-bl);
// 保证下标范围
if(r>i && r<=n && a[r] == br)
cnt++;
}
printf("%d\n", cnt);
}
}
笔者水平有限,若有错误欢迎纠正