D. Array Differentiation
[link](Problem - D - Codeforces)
题意
给你一个n个整数的序列a1,a2,…,an。
是否存在一个n个整数的序列b1,b2,…,bn,使下面的性质成立?
对于每个1≤i≤n,存在两个(不一定是不同的)指数j和k(1≤j,k≤n),使得ai=bj-bk
题解
把每一个bi 当作一个点的点权,则ai 就是 i - k这条边的边权,如果存在序列b 等价于序列b中的子序列可以构成一个环使得边权和序列a中的数对应,如果存在这么一个环,那么边权就可以通过加减抵消变成0,等价于通过每一个a正负0判断是否能构成一个环。
Code
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <set>
#include <queue>
#include <vector>
#include <map>
#include <unordered_map>
#include <cmath>
#include <stack>
#include <iomanip>
#define x first
#define y second
#define eps 1e-7
using namespace std;
typedef long double ld;
typedef long long LL;
typedef pair<int, int> PII;
typedef unsigned long long ULL;
const int N = 5e4 + 10, M = 30010, INF = 0x3f3f3f3f, P = 131, mod = 1e9 + 7;
int dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1};
int n, m;
int a[N];
bool dfs(int u, int sum, int ok) { // 不能是空环
if (u > n) {
return sum == 0 && ok;
}
bool ret = false; // dfs深搜,树形结构
ret |= dfs(u + 1, sum, ok);
ret |= dfs(u + 1, sum + a[u], 1);
ret |= dfs(u + 1, sum - a[u], 1);
return ret;
}
int main () {
cin.tie(nullptr)->sync_with_stdio(false);
int T;
cin >> T;
while (T --) {
cin >> n;
for (int i = 1; i <= n; i ++ ) cin >> a[i];
if (dfs(1, 0, 0)) puts("YES");
else puts("NO");
}
return 0;
}
353

被折叠的 条评论
为什么被折叠?



