CodeForces 1388D Captain Flint and Treasure
Captain Fint is involved in another treasure hunt, but have found only one strange problem. The problem may be connected to the treasure's location or may not. That's why captain Flint decided to leave the solving the problem to his crew and offered an absurdly high reward: one day off. The problem itself sounds like this...
There are two arrays aa and bb of length nn. Initially, an ansans is equal to 00 and the following operation is defined:
- Choose position ii (1≤i≤n1≤i≤n);
- Add aiai to ansans;
- If bi≠−1bi≠−1 then add aiai to abiabi.
What is the maximum ansans you can get by performing the operation on each ii (1≤i≤n1≤i≤n) exactly once?
Uncle Bogdan is eager to get the reward, so he is asking your help to find the optimal order of positions to perform the operation on them.
Input
The first line contains the integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of arrays aa and bb.
The second line contains nn integers a1,a2,…,ana1,a2,…,an (−106≤ai≤106−106≤ai≤106).
The third line contains nn integers b1,b2,…,bnb1,b2,…,bn (1≤bi≤n1≤bi≤n or bi=−1bi=−1).
Additional constraint: it's guaranteed that for any ii (1≤i≤n1≤i≤n) the sequence bi,bbi,bbbi,…bi,bbi,bbbi,… is not cyclic, in other words it will always end with −1−1.
Output
In the first line, print the maximum ansans you can get.
In the second line, print the order of operations: nn different integers p1,p2,…,pnp1,p2,…,pn (1≤pi≤n1≤pi≤n). The pipi is the position which should be chosen at the ii-th step. If there are multiple orders, print any of them.
Examples
Input3 1 2 3 2 3 -1Output10 1 2 3Input2 -1 100 2 -1Output99 2 1Input10 -10 -1 2 2 5 -2 -3 -4 2 -6 -1 -1 2 2 -1 5 5 7 7 9Output-9 3 5 6 1 9 4 10 7 8 2
拓扑排序b,然后判断每一个a的值小于0就加入末尾,大于0就加入开头
#define _CRT_SECURE_NO_WARNINGS #include<cstdio> #include<cstring> #include<algorithm> #include<iostream> #include<cstdlib> #include<cmath> #include<map> #include<queue> using namespace std; typedef long long ll; #define Inf 0x3f3f3f3f #define Maxn 20 const int N = 2e5 + 10; int n, m, cnt = 1; int du[N], b[N], p[N]; ll a[N]; queue<int> Q; ll ans = 0; int main() { scanf("%d", &n); for (int i = 1; i <= n; ++i) scanf("%I64d", &a[i]); for (int i = 1; i <= n; ++i) { scanf("%d", &b[i]); if (b[i] != -1)du[b[i]]++; } for (int i = 1; i <= n; ++i) if (!du[i]) Q.push(i); int l = 1, r = n, x; while (!Q.empty()) { x = Q.front(); Q.pop(); ans += a[x]; if (a[x] < 0) { p[r] = x; --r; if (b[x] != -1) { --du[b[x]]; if (!du[b[x]]) Q.push(b[x]); } } else { p[l] = x; ++l; if (b[x] != -1) { a[b[x]] += a[x]; --du[b[x]]; if (!du[b[x]]) Q.push(b[x]); } } } printf("%I64d\n", ans); for (int i = 1; i <= n; ++i) printf("%d ", p[i]); puts(""); return 0; }

浙公网安备 33010602011771号