Wunder Fund Round 2016 (Div. 1 + Div. 2 combined) F. Double Knapsack 鸽巢原理 构造
题目连接:
http://www.codeforces.com/contest/618/problem/F
Description
You are given two multisets A and B. Each multiset has exactly n integers each between 1 and n inclusive. Multisets may contain multiple copies of the same number.
You would like to find a nonempty subset of A and a nonempty subset of B such that the sum of elements in these subsets are equal. Subsets are also multisets, i.e. they can contain elements with equal values.
If no solution exists, print - 1. Otherwise, print the indices of elements in any such subsets of A and B that have the same sum.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 1 000 000) — the size of both multisets.
The second line contains n integers, denoting the elements of A. Each element will be between 1 and n inclusive.
The third line contains n integers, denoting the elements of B. Each element will be between 1 and n inclusive.
Output
If there is no solution, print a single integer - 1. Otherwise, your solution should be printed on four lines.
The first line should contain a single integer ka, the size of the corresponding subset of A. The second line should contain ka distinct integers, the indices of the subset of A.
The third line should contain a single integer kb, the size of the corresponding subset of B. The fourth line should contain kb distinct integers, the indices of the subset of B.
Elements in both sets are numbered from 1 to n. If there are multiple possible solutions, print any of them.
Sample Input
10
10 10 10 10 10 10 10 10 10 10
10 9 8 7 6 5 4 3 2 1
Sample Output
1
2
3
5 8 10
Hint
题意
给你a集合和b集合,两个集合里面都恰好有n个数,每个数都是在[1,n]范围内的数
然后你需要找到a集合的一个子集,b集合的一个子集,使得这两个子集的和相同
然后输出出来。
题解:
令Ai = a0+a1+...+ai,Bi = b0+b1+...+bi
其中A0 = 0,B0 = 0;
我们假设An
显然有(n+1)对Ai-Bj,且0<=(Ai-Bj)<=n-1
根据鸽巢原理,显然可以找到两对Ai-Bj = Ai'-Bj'
所以只要输出这两队就好了
边扫边存下来就好了
然后这道题就结束了
代码
#include
using namespace std;
const int maxn = 1e6+7;
const long long inf = 1e9;
long long a[maxn],b[maxn];
paird[maxn*2];int main()
{int n;scanf("%d",&n);for(int i=1;i<=n;i++)scanf("%lld",&a[i]);for(int i=1;i<=n;i++)scanf("%lld",&b[i]);for(int i=0;i
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
