solution
stringlengths 11
983k
| difficulty
int64 0
21
| language
stringclasses 2
values |
---|---|---|
#include <bits/stdc++.h>
using namespace std;
const int N = 200;
const int M = 20000;
const int oo = 0X10101010;
int mym;
int S, T;
struct adj {
int ano, cap, wei, nex;
} adj[M];
int nod[N];
void insert(int x, int y, int c, int w) {
adj[mym].ano = y;
adj[mym].cap = c;
adj[mym].wei = w;
adj[mym].nex = nod[x];
nod[x] = mym++;
adj[mym].ano = x;
adj[mym].cap = 0;
adj[mym].wei = -w;
adj[mym].nex = nod[y];
nod[y] = mym++;
}
bool use[N];
int dis[N], pre[N], lx[N];
int bfs() {
int p = 0, q = 0, x, e;
memset(use, 0, sizeof(use));
memset(dis, 0X10, sizeof(dis));
lx[q++] = S;
use[S] = true;
dis[S] = 0;
pre[S] = -1;
while (p != q) {
x = lx[p++];
p %= N;
for (e = nod[x]; e != -1; e = adj[e].nex) {
if (adj[e].cap > 0)
if (adj[e].wei + dis[x] < dis[adj[e].ano]) {
dis[adj[e].ano] = adj[e].wei + dis[x];
pre[adj[e].ano] = e;
if (!use[adj[e].ano]) {
use[adj[e].ano] = true;
lx[q++] = adj[e].ano;
q %= N;
}
}
}
use[x] = false;
}
return dis[T];
}
int mincostmaxflow() {
int ans = 0, hav, x;
while (bfs() != oo) {
x = T;
hav = oo;
while (x != S) {
if (adj[pre[x]].cap < hav) hav = adj[pre[x]].cap;
x = adj[pre[x] ^ 1].ano;
}
x = T;
while (x != S) {
ans += hav * adj[pre[x]].wei;
adj[pre[x]].cap -= hav;
adj[pre[x] ^ 1].cap += hav;
x = adj[pre[x] ^ 1].ano;
}
}
return ans;
}
vector<int> ans[80];
int tt() {
int i = 0, j = 0, n = 0, k = 0, e = 0;
int a[80] = {0}, b[80] = {0};
memset(nod, 0XFF, sizeof(nod));
mym = 0;
scanf("%d%d", &n, &k);
for (i = 1; i <= n; i++) {
scanf("%d%d", a + i, b + i);
}
S = 0;
T = n + k + 1 + 1;
for (i = 0; i <= k + 1; i++) ans[i].clear();
for (i = 1; i <= n; i++) {
insert(S, i, 1, 0);
for (j = 1; j <= k; j++) {
insert(i, n + j, 1, -(a[i] + b[i] * (j - 1)));
}
insert(i, n + k + 1, 1, -(b[i] * (k - 1)));
}
for (i = 1; i <= k; i++) {
insert(n + i, T, 1, 0);
}
insert(n + k + 1, T, n - k, 0);
mincostmaxflow();
for (i = 1; i <= n; i++) {
for (e = nod[i]; e != -1; e = adj[e].nex) {
if (adj[e].cap == 0) {
ans[adj[e].ano - n].push_back(i);
}
}
}
printf("%d\n", k + 2 * (n - k));
for (i = 1; i <= k - 1; i++) {
printf("%d ", ans[i][0]);
}
for (i = 0; i < ans[k + 1].size(); i++) {
printf("%d ", ans[k + 1][i]);
printf("%d ", -ans[k + 1][i]);
}
printf("%d\n", ans[k][0]);
return 0;
}
int main() {
int o = 0;
scanf("%d", &o);
while (o--) {
tt();
}
return 0;
}
| 12 | CPP |
#include <bits/stdc++.h>
using namespace std;
const int MX = 80;
int n, k;
array<int, 3> m[MX];
long long dp[MX][MX];
int dpb[MX][MX];
void solve() {
cin >> n >> k;
for (int i = (0); i < (n); ++i) {
cin >> m[i][1] >> m[i][0];
m[i][2] = i + 1;
}
sort(m, m + n);
for (int i = (0); i < (n + 1); ++i) {
memset((dp[i]), -1, (k + 1) * sizeof(dp[i][0]));
memset((dpb[i]), -1, (k + 1) * sizeof(dpb[i][0]));
}
dp[0][0] = 0;
for (int i = (0); i < (n); ++i)
for (int j = (0); j < (k + 1); ++j) {
if (dp[i][j] == -1) continue;
auto [b, a, _id] = m[i];
if (dp[i + 1][j] < dp[i][j] + (k - 1) * b) {
dp[i + 1][j] = dp[i][j] + (k - 1) * b;
dpb[i + 1][j] = 0;
}
if (j < k && dp[i + 1][j + 1] < dp[i][j] + a + j * b) {
dp[i + 1][j + 1] = dp[i][j] + a + j * b;
dpb[i + 1][j + 1] = 1;
}
}
vector<int> mf = vector<int>(k);
vector<int> rit = vector<int>();
rit.reserve(n - k);
int cp = k;
for (int i = (n)-1; i >= (0); --i) {
auto [b, a, id] = m[i];
if (dpb[i + 1][cp])
mf[--cp] = id;
else
rit.push_back(id);
}
cout << 2 * n - k << '\n';
for (int i = (0); i < (k - 1); ++i) cout << mf[i] << ' ';
for (int i = (0); i < (n - k); ++i) cout << rit[i] << ' ' << -rit[i] << ' ';
cout << mf[k - 1] << '\n';
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int t;
cin >> t;
while (t--) {
solve();
}
}
| 12 | CPP |
#include <bits/stdc++.h>
using namespace std;
const int MX = 80;
const long long inf = 1e15;
struct info {
long long a, b, indx;
bool operator<(const info& s) const { return b < s.b; }
};
long long n, c;
info ara[MX];
vector<long long> add, rem;
long long dp[MX][MX], choose[MX][MX];
long long func(long long pos, long long lim) {
if (pos >= n) return lim ? -inf : 0;
long long& r = dp[pos][lim];
if (r != -1) return r;
long long r1 = 0, r2 = 0;
r1 = ara[pos].b * (c - 1) + func(pos + 1, lim);
if (lim) r2 = ara[pos].a + ara[pos].b * (c - lim) + func(pos + 1, lim - 1);
if (r1 < r2) choose[pos][lim] = 1;
return r = max(r1, r2);
}
int main() {
long long i, j, k;
long long t;
cin >> t;
while (t--) {
cin >> n >> c;
for (i = 0; i < n; ++i) {
info s;
cin >> s.a >> s.b;
s.indx = i + 1;
ara[i] = s;
}
sort(ara, ara + n);
memset(dp, -1, sizeof dp);
memset(choose, 0, sizeof choose);
func(0, c);
long long pos = 0, lim = c;
while (pos < n) {
if (choose[pos][lim]) {
add.push_back(ara[pos].indx);
lim--;
} else {
rem.push_back(ara[pos].indx);
}
pos++;
}
cout << add.size() + 2 * rem.size() << endl;
for (i = 0; i + 1 < add.size(); ++i) cout << add[i] << " ";
for (i = 0; i < rem.size(); ++i) cout << rem[i] << " " << -rem[i] << " ";
cout << add.back() << endl;
add.clear(), rem.clear();
}
}
| 12 | CPP |
#include <bits/stdc++.h>
using namespace std;
constexpr static int MAXN = 80;
int n, k;
int a[MAXN], b[MAXN];
int dp[MAXN][MAXN];
bool added[MAXN][MAXN];
bool used[MAXN];
void solve() {
cin >> n >> k;
for (int i = 0; i < n; i++) cin >> a[i] >> b[i];
vector<pair<int, int>> bval(n);
for (int i = 0; i < n; i++) bval[i] = {b[i], i};
sort(bval.begin(), bval.end());
for (int i = 0; i <= n; i++)
for (int j = 0; j <= k; j++) dp[i][j] = -1e9, added[i][j] = false;
dp[0][0] = 0;
for (int i = 0; i < n; i++) {
int l = bval[i].second;
for (int j = 0; j <= k; j++) {
dp[i + 1][j] = dp[i][j] + (k - 1) * b[l];
if (j == 0) continue;
int cost = a[l] + (j - 1) * b[l];
if (dp[i + 1][j] < dp[i][j - 1] + cost) {
dp[i + 1][j] = dp[i][j - 1] + cost;
added[i + 1][j] = true;
}
}
}
for (int i = 0; i < n; i++) used[i] = false;
vector<int> c;
int j = k;
for (int i = n; i > 0; i--) {
if (added[i][j]) {
c.push_back(bval[i - 1].second);
used[c.back()] = true;
j--;
}
}
reverse(c.begin(), c.end());
vector<int> moves;
for (int i = 0; i + 1 < c.size(); i++) moves.push_back(c[i] + 1);
for (int i = 0; i < n; i++)
if (!used[i]) moves.push_back(i + 1), moves.push_back(-(i + 1));
moves.push_back(c.back() + 1);
cout << moves.size() << endl;
for (int i = 0; i < moves.size(); i++)
cout << moves[i] << (i + 1 == moves.size() ? '\n' : ' ');
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int T;
cin >> T;
while (T--) {
solve();
}
}
| 12 | CPP |
#include <bits/stdc++.h>
using namespace std;
const int MAX = 80;
int f[MAX][MAX];
bool take[MAX][MAX];
void run_case() {
for (int i = 0; i < MAX; i++) {
for (int j = 0; j < MAX; j++) {
f[i][j] = -1000000000;
take[i][j] = false;
}
}
int n, k;
cin >> n >> k;
struct item {
int first, second, ind;
};
vector<item> a(n);
for (int i = 0; i < n; i++) {
cin >> a[i].first >> a[i].second;
a[i].ind = i;
}
sort(a.begin(), a.end(),
[&](const item& w, const item& v) { return w.second < v.second; });
f[n][k] = 0;
for (int i = n - 1; i >= 0; i--) {
for (int j = 0; j <= k; j++) {
f[i][j] = f[i + 1][j] + a[i].second * (k - 1);
int cost = f[i + 1][j + 1] + a[i].first + a[i].second * j;
if (j < k && cost > f[i][j]) {
f[i][j] = cost;
take[i][j] = true;
}
}
}
cout << k + 2 * (n - k) << '\n';
int j = 0;
vector<int> taken, shrek;
for (int i = 0; i < n; i++) {
if (take[i][j]) {
taken.push_back(i);
j++;
} else {
shrek.push_back(i);
}
}
assert(taken.size() == k);
for (int i = 0; i + 1 < k; i++) cout << a[taken[i]].ind + 1 << ' ';
for (int i = 0; i < n - k; i++)
cout << a[shrek[i]].ind + 1 << ' ' << -a[shrek[i]].ind - 1 << ' ';
cout << a[taken[k - 1]].ind + 1 << '\n';
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int T;
cin >> T;
while (T--) run_case();
return 0;
}
| 12 | CPP |
#include <bits/stdc++.h>
using namespace std;
const int inf = 0x3f3f3f3f;
struct Edge {
int to, val, next, cost;
} edge[25086];
int s, t;
int cnt = -1;
int head[25086];
queue<int> q;
int d[25086];
int cur[25086];
int inq[25086];
int vis[25086];
int costsum;
void addEdge(int u, int v, int w, int f) {
cnt++;
edge[cnt].to = v;
edge[cnt].val = w;
edge[cnt].next = head[u];
edge[cnt].cost = f;
head[u] = cnt;
cnt++;
edge[cnt].to = u;
edge[cnt].val = 0;
edge[cnt].next = head[v];
edge[cnt].cost = -f;
head[v] = cnt;
}
bool bfs() {
memset(d, 0x3f, sizeof(d));
memset(vis, 0, sizeof(vis));
d[s] = 0;
q.push(s);
inq[s] = 1;
while (!q.empty()) {
int u = q.front();
q.pop();
inq[u] = 0;
for (int i = head[u]; i != -1; i = edge[i].next) {
int v = edge[i].to;
cur[v] = head[v];
int f = edge[i].cost;
if (d[v] > d[u] + f && edge[i].val > 0) {
d[v] = d[u] + f;
if (!inq[v]) {
q.push(v);
inq[v] = 1;
}
}
}
}
return d[t] != inf;
}
int dfs(int u, int flow) {
vis[u] = 1;
int nowflow = 0;
if (u == t) return flow;
for (int i = cur[u]; i != -1; i = edge[i].next) {
cur[u] = i;
int v = edge[i].to;
int w = edge[i].val;
int f = edge[i].cost;
if (d[v] == d[u] + f && w > 0 && !vis[v]) {
int k = dfs(v, min(flow - nowflow, w));
if (k > 0) {
edge[i].val -= k;
edge[i ^ 1].val += k;
nowflow += k;
costsum += f * k;
if (nowflow == flow) break;
}
}
}
vis[u] = 0;
if (!nowflow) d[u] = inf;
return nowflow;
}
int dinic() {
int ans = 0;
while (bfs()) {
ans += dfs(s, inf);
}
return ans;
}
int T;
int n, k, a, b;
int opt[25086];
int main() {
scanf("%d", &T);
while (T--) {
memset(head, -1, sizeof(head)), cnt = -1;
scanf("%d%d", &n, &k);
s = 0, t = 2 * n + 1, costsum = 0;
for (int i = 1; i <= n; i++) {
scanf("%d%d", &a, &b);
addEdge(s, i, 1, 0), addEdge(i + n, t, 1, 0);
for (int j = 1; j <= n; j++) {
if (j < k)
addEdge(i, j + n, 1, -(a + (j - 1) * b));
else if (j < n)
addEdge(i, j + n, 1, -(k - 1) * b);
else
addEdge(i, j + n, 1, -(a + (k - 1) * b));
}
}
dinic();
for (int i = 1; i <= n; i++) {
for (int j = head[i]; j != -1; j = edge[j].next) {
if (!edge[j].val) {
opt[edge[j].to - n] = i;
break;
}
}
}
printf("%d\n", k - 1 + (n - k) * 2 + 1);
for (int i = 1; i <= n; i++) {
if (i < k || i == n)
printf("%d ", opt[i]);
else
printf("%d %d ", opt[i], -opt[i]);
}
puts("");
}
}
| 12 | CPP |
#include <bits/stdc++.h>
#pragma GCC target("avx2")
#pragma GCC optimization("O3")
#pragma GCC optimization("unroll-loops")
using namespace std;
template <typename T>
void DBG(const char* name, T&& H) {
cerr << name << " = " << H << ')' << '\n';
}
template <typename T, typename... Args>
void DBG(const char* names, T&& H, Args&&... args) {
const char* NEXT = strchr(names + 1, ',');
cerr.write(names, NEXT - names) << " = " << H << " |";
DBG(NEXT + 1, args...);
}
using ll = long long;
using ld = long double;
const ll mod = 1e9 + 7;
const ld PI = acos(-1.0);
const ll maxN = 1e5 + 1;
struct Hungarian {
using T = int;
int N;
vector<vector<T>> cost;
vector<int> Lmate, Rmate;
T minCost = 0;
Hungarian(int n = 1e2) {
N = n;
cost.resize(n, vector<T>(n));
Lmate.resize(n, -1);
Rmate.resize(n, -1);
}
void compute() {
vector<T> a(N), b(N);
for (int i = 0; i < N; i++) {
a[i] = cost[i][0];
for (int j = 1; j < N; j++) {
a[i] = min(a[i], cost[i][j]);
}
}
for (int i = 0; i < N; i++) {
b[i] = cost[0][i] - a[0];
for (int j = 1; j < N; j++) {
b[i] = min(b[i], cost[j][i] - a[j]);
}
}
int matched = 0;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (Rmate[j] != -1) continue;
if (abs(cost[i][j] - a[i] - b[j]) == 0) {
Lmate[i] = j;
Rmate[j] = i;
matched++;
break;
}
}
}
vector<T> dist(N);
vector<int> dad(N), seen(N);
while (matched < N) {
int s = 0;
while (Lmate[s] != -1) s++;
fill(dad.begin(), dad.end(), -1);
fill(seen.begin(), seen.end(), 0);
for (int k = 0; k < N; k++) {
dist[k] = cost[s][k] - a[s] - b[k];
}
int j = 0;
while (true) {
j = -1;
for (int k = 0; k < N; k++) {
if (seen[k]) continue;
if ((j == -1) || (dist[k] < dist[j])) j = k;
}
seen[j] = 1;
if (Rmate[j] == -1) break;
int i = Rmate[j];
for (int k = 0; k < N; k++) {
if (seen[k]) continue;
int newDist = dist[j] + cost[i][k] - a[i] - b[k];
if (dist[k] > newDist) {
dist[k] = newDist;
dad[k] = j;
}
}
}
for (int k = 0; k < N; k++) {
if ((k == j) || (!seen[k])) continue;
int i = Rmate[k];
a[i] -= dist[k] - dist[j];
b[k] += dist[k] - dist[j];
}
a[s] += dist[j];
while (dad[j] >= 0) {
int d = dad[j];
Rmate[j] = Rmate[d];
Lmate[Rmate[j]] = j;
j = d;
}
Rmate[j] = s;
Lmate[s] = j;
matched++;
}
for (int i = 0; i < N; i++) {
minCost += cost[i][Lmate[i]];
}
}
};
void Solve() {
int n, k;
cin >> n >> k;
Hungarian order(n);
vector<int> a(n), b(n);
for (int i = 0; i < n; i++) {
cin >> a[i] >> b[i];
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < k - 1; j++) {
order.cost[i][j] = -(a[i] + j * b[i]);
}
for (int j = k - 1; j < n - 1; j++) {
order.cost[i][j] = -((k - 1) * b[i]);
}
order.cost[i][n - 1] = -(a[i] + (k - 1) * b[i]);
}
order.compute();
cout << k + 2 * (n - k) << '\n';
for (int i = 0; i < k - 1; i++) {
cout << order.Rmate[i] + 1 << " ";
}
for (int i = k - 1; i < n - 1; i++) {
cout << order.Rmate[i] + 1 << " " << -(order.Rmate[i] + 1) << " ";
}
cout << order.Rmate[n - 1] + 1 << '\n';
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int tt = 1;
cin >> tt;
while (tt--) {
Solve();
}
return 0;
}
| 12 | CPP |
#include <bits/stdc++.h>
using namespace std;
const int INF = 1e9 + 1e8;
int main() {
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
int tcase;
cin >> tcase;
while (tcase--) {
int n, k;
cin >> n >> k;
vector<int> a(n + 1), b(n + 1), id(n + 1);
for (int i = 1; i <= n; i++) cin >> a[i] >> b[i], id[i] = i;
sort(id.begin() + 1, id.begin() + n + 1,
[&](int u, int v) { return b[u] < b[v]; });
vector<vector<int>> dp(n + 1, vector<int>(k + 1, -INF)),
prv(n + 1, vector<int>(k + 1, 0));
dp[0][0] = 0;
for (int i = 1; i <= n; i++) {
for (int j = 0; j <= k; j++) {
dp[i][j] = dp[i - 1][j];
if (j) {
if (dp[i][j] < dp[i - 1][j - 1] + a[id[i]] - b[id[i]] * (k - j)) {
dp[i][j] = dp[i - 1][j - 1] + a[id[i]] - b[id[i]] * (k - j);
prv[i][j] = 1;
}
}
}
}
vector<int> chk(n + 1, 0);
int cur_i = n, cur_j = k;
while (cur_i) {
if (prv[cur_i][cur_j])
chk[cur_i] = 1, cur_i--, cur_j--;
else
cur_i--;
}
vector<int> ans1, ans2;
for (int i = 1; i <= n; i++)
if (chk[i]) ans1.push_back(id[i]);
for (int i = 1; i <= n; i++)
if (!chk[i]) ans2.push_back(id[i]);
vector<int> rlt;
for (int i = 0; i < ans1.size() - 1; i++) rlt.push_back(ans1[i]);
for (auto it : ans2) rlt.push_back(it), rlt.push_back(-it);
rlt.push_back(ans1[ans1.size() - 1]);
cout << rlt.size() << "\n";
for (int i = 0; i < rlt.size(); i++)
cout << rlt[i] << " \n"[i == rlt.size() - 1];
}
return 0;
}
| 12 | CPP |
#include <bits/stdc++.h>
using namespace std;
const long long mod = 1000000007;
const long long INF = (long long)1000000007 * 1000000007;
const long double eps = 1e-8;
const long double pi = acos(-1.0);
int dx[4] = {1, -1, 0, 0};
int dy[4] = {0, 0, 1, -1};
template <class T>
bool chmax(T &a, const T &b) {
if (a < b) {
a = b;
return 1;
}
return 0;
}
template <class T>
bool chmin(T &a, const T &b) {
if (b < a) {
a = b;
return 1;
}
return 0;
}
template <class Cap, class Cost>
struct MinCostFlow {
public:
MinCostFlow() {}
MinCostFlow(int n) : _n(n), g(n) {}
int add_edge(int from, int to, Cap cap, Cost cost) {
assert(0 <= from && from < _n);
assert(0 <= to && to < _n);
int m = int(pos.size());
pos.push_back({from, int(g[from].size())});
g[from].push_back(_edge{to, int(g[to].size()), cap, cost});
g[to].push_back(_edge{from, int(g[from].size()) - 1, 0, -cost});
return m;
}
struct edge {
int from, to;
Cap cap, flow;
Cost cost;
};
edge get_edge(int i) {
int m = int(pos.size());
assert(0 <= i && i < m);
auto _e = g[pos[i].first][pos[i].second];
auto _re = g[_e.to][_e.rev];
return edge{
pos[i].first, _e.to, _e.cap + _re.cap, _re.cap, _e.cost,
};
}
std::vector<edge> edges() {
int m = int(pos.size());
std::vector<edge> result(m);
for (int i = 0; i < m; i++) {
result[i] = get_edge(i);
}
return result;
}
std::pair<Cap, Cost> flow(int s, int t) {
return flow(s, t, std::numeric_limits<Cap>::max());
}
std::pair<Cap, Cost> flow(int s, int t, Cap flow_limit) {
return slope(s, t, flow_limit).back();
}
std::vector<std::pair<Cap, Cost>> slope(int s, int t) {
return slope(s, t, std::numeric_limits<Cap>::max());
}
std::vector<std::pair<Cap, Cost>> slope(int s, int t, Cap flow_limit) {
assert(0 <= s && s < _n);
assert(0 <= t && t < _n);
assert(s != t);
std::vector<Cost> dual(_n, 0), dist(_n);
std::vector<int> pv(_n), pe(_n);
std::vector<bool> vis(_n);
auto dual_ref = [&]() {
std::fill(dist.begin(), dist.end(), std::numeric_limits<Cost>::max());
std::fill(pv.begin(), pv.end(), -1);
std::fill(pe.begin(), pe.end(), -1);
std::fill(vis.begin(), vis.end(), false);
struct Q {
Cost key;
int to;
bool operator<(Q r) const { return key > r.key; }
};
std::priority_queue<Q> que;
dist[s] = 0;
que.push(Q{0, s});
while (!que.empty()) {
int v = que.top().to;
que.pop();
if (vis[v]) continue;
vis[v] = true;
if (v == t) break;
for (int i = 0; i < int(g[v].size()); i++) {
auto e = g[v][i];
if (vis[e.to] || !e.cap) continue;
Cost cost = e.cost - dual[e.to] + dual[v];
if (dist[e.to] - dist[v] > cost) {
dist[e.to] = dist[v] + cost;
pv[e.to] = v;
pe[e.to] = i;
que.push(Q{dist[e.to], e.to});
}
}
}
if (!vis[t]) {
return false;
}
for (int v = 0; v < _n; v++) {
if (!vis[v]) continue;
dual[v] -= dist[t] - dist[v];
}
return true;
};
Cap flow = 0;
Cost cost = 0, prev_cost = -1;
std::vector<std::pair<Cap, Cost>> result;
result.push_back({flow, cost});
while (flow < flow_limit) {
if (!dual_ref()) break;
Cap c = flow_limit - flow;
for (int v = t; v != s; v = pv[v]) {
c = std::min(c, g[pv[v]][pe[v]].cap);
}
for (int v = t; v != s; v = pv[v]) {
auto &e = g[pv[v]][pe[v]];
e.cap -= c;
g[v][e.rev].cap += c;
}
Cost d = -dual[s];
flow += c;
cost += c * d;
if (prev_cost == d) {
result.pop_back();
}
result.push_back({flow, cost});
prev_cost = cost;
}
return result;
}
private:
int _n;
struct _edge {
int to, rev;
Cap cap;
Cost cost;
};
std::vector<std::pair<int, int>> pos;
std::vector<std::vector<_edge>> g;
};
using edge = MinCostFlow<int, int>::edge;
const int inf = 10000000;
int n, k;
vector<int> a(n), b(n);
void solve() {
MinCostFlow<int, int> mcf(n + k + 5);
int ans = inf * n;
int S = n + k + 1;
for (int i = 0; i < n; i++) {
mcf.add_edge(i, n + k, 1, inf - (k - 1) * b[i]);
for (int j = 0; j < k; j++) {
mcf.add_edge(i, n + j, 1, inf - a[i] - j * b[i]);
}
}
for (int i = 0; i < n; i++) {
mcf.add_edge(S, i, 1, 0);
}
for (int j = 0; j < k; j++) {
mcf.add_edge(n + j, S + 1, 1, 0);
}
mcf.add_edge(n + k, S + 1, n - k, 0);
pair<int, int> p = mcf.flow(S, S + 1);
auto es = mcf.edges();
vector<int> v(k);
vector<bool> used(n);
for (auto e : es) {
if (e.to - n < 0 || e.to - n >= k) continue;
if (e.flow == 1) {
v[e.to - n] = e.from;
used[e.from] = true;
}
}
printf("%d\n", 2 * n - k);
for (int i = 0; i < k - 1; i++) {
printf("%d ", v[i] + 1);
}
for (int i = 0; i < n; i++) {
if (!used[i]) {
printf("%d %d ", i + 1, -i - 1);
}
}
printf("%d\n", v[k - 1] + 1);
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout << fixed << setprecision(50);
int t;
scanf("%d", &t);
for (int i = 0; i < t; i++) {
scanf("%d%d", &n, &k);
a.resize(n);
b.resize(n);
for (int i = 0; i < n; i++) scanf("%d%d", &a[i], &b[i]);
solve();
}
}
| 12 | CPP |
#include <bits/stdc++.h>
using namespace std;
struct ANS {
long long sss, i;
ANS *to;
} dp[80][80];
ANS max_get(ANS a, ANS b, ANS *aa, ANS *bb, long long i) {
ANS s;
if (a.sss > b.sss) {
s.sss = a.sss;
s.i = 0;
s.to = aa;
} else {
s.sss = b.sss;
s.i = i;
s.to = bb;
}
return s;
}
struct node {
long long a, b, i;
bool operator<(const node x) const { return b < x.b; }
} mp[80];
long long n, m, T;
bool vis[80];
void print(ANS *x) {
if (x == NULL) return;
print(x->to);
if (x->i) {
printf("%lld ", mp[x->i].i);
vis[x->i] = 1;
}
}
int main() {
scanf("%lld", &T);
while (T--) {
memset(vis, 0, sizeof(vis));
scanf("%lld%lld", &n, &m);
for (long long i = 1; i <= n; i++) {
scanf("%lld%lld", &mp[i].a, &mp[i].b);
mp[i].i = i;
}
sort(mp + 1, mp + n + 1);
if (n <= m) {
printf("%lld\n", n);
for (long long i = 1; i <= n; i++) printf("%lld ", mp[i].i);
printf("\n");
continue;
}
for (long long i = 0; i <= n; i++)
for (long long j = 0; j <= m; j++) {
dp[i][j].sss = -1e18;
dp[i][j].i = 0;
dp[i][j].to = NULL;
}
dp[0][0].sss = 0;
for (long long i = 1; i <= n; i++) {
dp[i][0].i = 0;
dp[i][0].to = &dp[i - 1][0];
dp[i][0].sss = dp[i - 1][0].sss + mp[i].b * (m - 1);
for (long long j = 1; j <= m; j++) {
ANS xa = dp[i - 1][j], xb = dp[i - 1][j - 1];
xa.sss += mp[i].b * (m - 1);
xb.sss += mp[i].b * (j - 1) + mp[i].a;
dp[i][j] = max_get(xa, xb, &dp[i - 1][j], &dp[i - 1][j - 1], i);
}
}
printf("%lld\n", 2 * n - m);
ANS re = dp[n][m];
while (!re.i) re = *(re.to);
print(re.to);
vis[re.i] = 1;
for (long long i = 1; i <= n; i++)
if (!vis[i]) printf("%lld -%lld ", mp[i].i, mp[i].i);
printf("%lld\n", mp[re.i].i);
}
return 0;
}
| 12 | CPP |
#include <bits/stdc++.h>
using namespace std;
const double eps = 1e-9;
const int inf = 2000000000;
const long long infLL = 9000000000000000000;
template <typename first, typename second>
ostream& operator<<(ostream& os, const pair<first, second>& p) {
return os << "(" << p.first << ", " << p.second << ")";
}
template <typename T>
ostream& operator<<(ostream& os, const vector<T>& v) {
os << "{";
for (auto it = v.begin(); it != v.end(); ++it) {
if (it != v.begin()) os << ", ";
os << *it;
}
return os << "}";
}
template <typename T>
ostream& operator<<(ostream& os, const set<T>& v) {
os << "[";
for (auto it = v.begin(); it != v.end(); ++it) {
if (it != v.begin()) os << ",";
os << *it;
}
return os << "]";
}
template <typename T>
ostream& operator<<(ostream& os, const multiset<T>& v) {
os << "[";
for (auto it = v.begin(); it != v.end(); ++it) {
if (it != v.begin()) os << ", ";
os << *it;
}
return os << "]";
}
template <typename first, typename second>
ostream& operator<<(ostream& os, const map<first, second>& v) {
os << "[";
for (auto it = v.begin(); it != v.end(); ++it) {
if (it != v.begin()) os << ", ";
os << it->first << " = " << it->second;
}
return os << "]";
}
void faltu() { cerr << '\n'; }
template <typename T>
void faltu(T a[], int n) {
for (int i = 0; i < n; ++i) cerr << a[i] << ' ';
cerr << '\n';
}
template <typename T, typename... hello>
void faltu(T arg, const hello&... rest) {
cerr << arg << ' ';
faltu(rest...);
}
int n, k;
vector<pair<pair<int, int>, int>> vec;
int dp[80][80];
vector<int> store;
int recur(int pos, int taken) {
if (pos == n) {
if (taken == k) return 0;
return -inf;
}
if (dp[pos][taken] != -1) return dp[pos][taken];
int ret = 0;
if (taken < k)
ret = vec[pos].first.second + vec[pos].first.first * taken +
recur(pos + 1, taken + 1);
ret = max(ret, vec[pos].first.first * (k - 1) + recur(pos + 1, taken));
dp[pos][taken] = ret;
return ret;
}
void print(int pos, int taken) {
if (pos == n) return;
if (taken < k && recur(pos, taken) == vec[pos].first.second +
vec[pos].first.first * taken +
recur(pos + 1, taken + 1)) {
store.push_back(vec[pos].second + 1);
print(pos + 1, taken + 1);
return;
}
if (recur(pos, taken) ==
vec[pos].first.first * (k - 1) + recur(pos + 1, taken)) {
store.push_back(-vec[pos].second - 1);
print(pos + 1, taken);
return;
}
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
;
int T;
cin >> T;
while (T--) {
memset(dp, -1, sizeof(dp));
vec.clear();
store.clear();
cin >> n >> k;
vec.resize(n);
for (int i = 0; i < n; ++i)
cin >> vec[i].first.second >> vec[i].first.first, vec[i].second = i;
sort(vec.begin(), vec.end());
cout << 2 * n - k << '\n';
print(0, 0);
for (int i = 0, j = 0; i < n && j < k - 1; ++i) {
if (store[i] > 0) {
++j;
cout << store[i] << " ";
}
}
for (int i = 0; i < n; ++i) {
if (store[i] < 0) {
cout << -store[i] << " " << store[i] << " ";
}
}
for (int i = n - 1; i >= 0; --i) {
if (store[i] > 0) {
cout << store[i] << '\n';
break;
}
}
}
}
| 12 | CPP |
#include <bits/stdc++.h>
using namespace std;
const int N = (1e2) + 10;
const int M = (1e5) + 10;
const int INF = (1e9) + 10;
const int maxn = 5e6 + 100;
int dp[N][N];
int p[N][N];
struct trr {
int first;
int second;
int poz;
};
bool comp(trr a, trr b) { return a.first < b.first; }
void solve() {
int n, k;
cin >> n >> k;
vector<trr> arr(n);
vector<int> ans[2];
for (int i = int(0); i < int(n); i++) {
int a, b;
cin >> a >> b;
arr[i] = {b, a, i + 1};
}
sort(arr.begin(), arr.end(), comp);
memset(dp, -1, sizeof(dp));
dp[0][0] = 0;
for (int i = int(0); i < int(n); i++) {
for (int j = int(0); j < int(k + 1); j++)
if (dp[i][j] >= 0) {
if (dp[i + 1][j + 1] < dp[i][j] + arr[i].first * j + arr[i].second) {
dp[i + 1][j + 1] = dp[i][j] + arr[i].first * j + arr[i].second;
p[i + 1][j + 1] = 1;
}
if (dp[i + 1][j] < dp[i][j] + arr[i].first * (k - 1)) {
dp[i + 1][j] = dp[i][j] + arr[i].first * (k - 1);
p[i + 1][j] = 0;
}
}
}
int pos = k;
for (int i = n; i >= 1; i--) {
ans[p[i][pos]].push_back(arr[i - 1].poz);
pos -= p[i][pos];
}
reverse(ans[0].begin(), ans[0].end());
reverse(ans[1].begin(), ans[1].end());
cout << ans[0].size() * 2 + ans[1].size() << endl;
for (int i = int(0); i < int(ans[1].size() - 1); i++)
cout << ans[1][i] << ' ';
for (int i = int(0); i < int(ans[0].size()); i++)
cout << ans[0][i] << ' ' << -ans[0][i] << ' ';
cout << ans[1][ans[1].size() - 1];
cout << endl;
}
int main() {
int t = 1;
cin >> t;
while (t) {
solve();
t--;
}
return 0;
}
| 12 | CPP |
#include <bits/stdc++.h>
using namespace std;
template <typename T>
ostream &operator<<(ostream &os, const vector<T> &v) {
os << '{';
string sep;
for (const auto &x : v) os << sep << x, sep = ", ";
return os << '}';
}
template <typename A, typename B>
ostream &operator<<(ostream &os, const pair<A, B> &p) {
return os << '(' << p.first << ", " << p.second << ')';
}
void dbg_out() { cerr << endl; }
template <typename Head, typename... Tail>
void dbg_out(Head H, Tail... T) {
cerr << ' ' << H;
dbg_out(T...);
}
template <typename T>
void output_vector(const vector<T> &v, bool add_one = false, int start = -1,
int end = -1) {
if (start < 0) start = 0;
if (end < 0) end = int(v.size());
for (int i = start; i < end; i++)
cout << v[i] + (add_one ? 1 : 0) << (i < end - 1 ? ' ' : '\n');
}
const int64_t INF64 = int64_t(2e18) + 5;
vector<int> assignment;
template <typename T>
int64_t hungarian(vector<vector<T>> costs) {
int n = int(costs.size());
int m = costs.empty() ? 0 : int(costs[0].size());
if (n > m) {
vector<vector<T>> new_costs(m, vector<T>(n));
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++) new_costs[j][i] = costs[i][j];
swap(costs, new_costs);
swap(n, m);
}
vector<int64_t> u(n + 1), v(m + 1);
vector<int> p(m + 1), way(m + 1);
for (int i = 1; i <= n; i++) {
vector<int64_t> min_v(m + 1, INF64);
vector<bool> used(m + 1, false);
p[0] = i;
int j0 = 0;
do {
used[j0] = true;
int i0 = p[j0], j1 = 0;
int64_t delta = INF64;
for (int j = 1; j <= m; j++)
if (!used[j]) {
int64_t cur = costs[i0 - 1][j - 1] - u[i0] - v[j];
if (cur < min_v[j]) {
min_v[j] = cur;
way[j] = j0;
}
if (min_v[j] < delta) {
delta = min_v[j];
j1 = j;
}
}
for (int j = 0; j <= m; j++)
if (used[j]) {
u[p[j]] += delta;
v[j] -= delta;
} else {
min_v[j] -= delta;
}
j0 = j1;
} while (p[j0] != 0);
do {
int j1 = way[j0];
p[j0] = p[j1];
j0 = j1;
} while (j0 != 0);
}
assignment = p;
return -v[0];
}
void run_case() {
int N, K;
cin >> N >> K;
vector<int> A(N), B(N);
for (int i = 0; i < N; i++) cin >> A[i] >> B[i];
vector<vector<int>> costs(N, vector<int>(N, 0));
for (int i = 0; i < N; i++)
for (int position = 0; position < N; position++)
if (position < K)
costs[i][position] = -(A[i] + position * B[i]);
else
costs[i][position] = -((K - 1) * B[i]);
int64_t score = -hungarian(costs);
;
vector<int> solution;
for (int k = 1; k < K; k++) solution.push_back(assignment[k]);
for (int k = K + 1; k <= N; k++) {
solution.push_back(assignment[k]);
solution.push_back(-assignment[k]);
}
solution.push_back(assignment[K]);
assert(int(solution.size()) == 2 * N - K);
cout << solution.size() << '\n';
output_vector(solution);
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int tests;
cin >> tests;
while (tests-- > 0) run_case();
}
| 12 | CPP |
#include <bits/stdc++.h>
using namespace std;
const long long NMAX = 200001;
const long long INF = (1 << 30);
const long long MOD = 1000000007;
const long long BLOCK = 101;
const long long nr_of_bits = 18;
int dp[76][76];
struct ura {
;
int first, second, third;
} v[76];
bool cmp(ura a, ura b) { return a.second < b.second; }
vector<int> sol;
vector<int> sel;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
int t;
cin >> t;
while (t--) {
int n, k, i, j;
cin >> n >> k;
sol.clear();
sel.clear();
for (i = 0; i <= n; i++) {
for (j = 0; j <= k; j++) dp[i][j] = 0;
}
for (i = 1; i <= n; i++) {
cin >> v[i].first >> v[i].second;
v[i].third = i;
}
sort(v + 1, v + n + 1, cmp);
for (i = 1; i <= n; i++) {
for (j = 0; j <= min(i, k); j++) {
if (i - 1 >= j)
dp[i][j] = max(dp[i][j], dp[i - 1][j] + (k - 1) * v[i].second);
if (j != 0) {
dp[i][j] = max(dp[i][j],
dp[i - 1][j - 1] + (j - 1) * v[i].second + v[i].first);
}
}
}
i = n, j = k;
while (i != 0) {
if (i - 1 >= j && dp[i][j] == dp[i - 1][j] + (k - 1) * v[i].second) {
sol.push_back(v[i].third);
sol.push_back(-v[i].third);
} else if (j != 0) {
if (dp[i][j] == dp[i - 1][j - 1] + (j - 1) * v[i].second + v[i].first) {
sel.push_back(v[i].third);
j--;
}
}
i--;
}
reverse(sel.begin(), sel.end());
cout << sol.size() + sel.size() << "\n";
for (int i = 0; i < sel.size() - 1; i++) {
cout << sel[i] << " ";
}
for (auto x : sol) {
cout << x << " ";
}
cout << sel.back() << "\n";
}
return 0;
}
| 12 | CPP |
#include <bits/stdc++.h>
using namespace std;
struct Edge {
long long to, dis, next, cost;
} edge[240050];
long long num = -1;
bool vis[100010];
long long mincost;
long long pre[100010], head[100010], cost[100010], last[100010], flow[100010],
n, k, a[110], b[110], s, t, maxflow;
long long to[110];
void add(long long f, long long t, long long dis, long long cost) {
edge[++num].to = t;
edge[num].dis = dis;
edge[num].next = head[f];
edge[num].cost = cost;
head[f] = num;
edge[++num].to = f;
edge[num].dis = 0;
edge[num].cost = -cost;
edge[num].next = head[t];
head[t] = num;
}
queue<long long> q;
bool spfa(long long s, long long t) {
memset(cost, 0x3f3f3f3f, sizeof cost);
memset(flow, 0x3f3f3f3f, sizeof flow);
memset(vis, 0, sizeof vis);
q.push(s);
vis[s] = 1;
cost[s] = 0;
pre[t] = -1;
while (!q.empty()) {
long long nowp = q.front();
q.pop();
vis[nowp] = 0;
for (long long i = head[nowp]; i != -1; i = edge[i].next) {
if (edge[i].dis > 0 && cost[edge[i].to] > cost[nowp] + edge[i].cost) {
cost[edge[i].to] = cost[nowp] + edge[i].cost;
pre[edge[i].to] = nowp;
last[edge[i].to] = i;
flow[edge[i].to] = min(flow[nowp], edge[i].dis);
if (!vis[edge[i].to]) {
vis[edge[i].to] = 1;
q.push(edge[i].to);
}
}
}
}
return pre[t] != -1;
}
void MCMF(long long s, long long t) {
while (spfa(s, t)) {
long long now = t;
maxflow += flow[t];
mincost += flow[t] * cost[t];
while (now != s) {
edge[last[now]].dis -= flow[t];
edge[last[now] ^ 1].dis += flow[t];
now = pre[now];
}
}
}
signed main() {
long long T;
cin >> T;
while (T--) {
num = -1;
memset(to, -1, sizeof to);
memset(head, -1, sizeof head);
cin >> n >> k;
for (long long i = 1; i <= n; i++) cin >> a[i] >> b[i];
memset(edge, 0, sizeof edge);
memset(pre, 0, sizeof pre);
memset(cost, 0, sizeof cost);
memset(flow, 0, sizeof flow);
memset(last, 0, sizeof last);
maxflow = mincost = 0;
s = 0;
t = 2 * n + 1;
for (long long i = 1; i <= n; i++) add(s, i, 1, 0), add(i + n, t, 1, 0);
for (long long i = 1; i <= n; i++) {
for (long long j = 1; j <= n; j++) {
long long nc = 0;
if (j <= k - 1)
nc = a[i] + b[i] * (j - 1ll);
else if (j != n)
nc = b[i] * (k - 1ll);
else
nc = a[i] + b[i] * (k - 1ll);
nc = 0x3f3f3f3f - nc;
add(i, j + n, 1, nc);
}
}
MCMF(s, t);
long long nowi = -1;
for (long long i = n * 4; i <= num; i += 2) {
nowi++;
if (edge[i].dis == 0) to[1 + nowi % n] = 1 + nowi / n;
}
cout << 2 * n - k << endl;
for (long long i = 1; i <= k - 1; i++) cout << to[i] << " ";
for (long long i = k; i < n; i++) cout << to[i] << " " << -to[i] << " ";
cout << to[n];
cout << endl;
}
return 0;
}
| 12 | CPP |
#include <bits/stdc++.h>
const int N = 77;
int e, n, k, a[N], b[N], id[N], s[N], p[N][N], f[N][N];
int cmp(int x, int y) { return b[x] < b[y]; }
int main() {
for (scanf("%d", &e); e; e--) {
memset(f, -1, sizeof f);
memset(p, 0, sizeof p);
memset(s, 0, sizeof s);
scanf("%d%d", &n, &k);
f[0][0] = 0;
int c = 0;
for (int i = 1; i <= n; i++) scanf("%d%d", a + i, b + i), id[i] = i;
std::sort(id + 1, id + 1 + n, cmp);
for (int i = 1; i <= n; i++)
for (int j = 0; j <= k && j <= i; j++) {
if (f[i - 1][j] != -1)
f[i][j] = f[i - 1][j] + b[id[i]] * (k - 1), p[i][j] = 0;
if (j > 0 && f[i - 1][j - 1] != -1) {
int t = f[i - 1][j - 1] + a[id[i]] + b[id[i]] * (j - 1);
if (t > f[i][j]) f[i][j] = t, p[i][j] = 1;
}
}
for (int i = n, j = k; i > 0; i--)
if (p[i][j]) s[id[i]] = 1, j--;
printf("%d\n", k + (n - k) * 2);
for (int i = 1; i <= n; i++)
if (s[id[i]]) {
c++;
if (c == k) {
c = id[i];
break;
}
printf("%d ", id[i]);
}
for (int i = 1; i <= n; i++)
if (!s[i]) printf("%d %d ", i, -i);
printf("%d\n", c);
}
return 0;
}
| 12 | CPP |
#include <bits/stdc++.h>
using namespace std;
const int Maxn = 88;
struct node {
int a, b, id;
} g[Maxn];
int f[Maxn][Maxn], s[Maxn];
bool flag[Maxn][Maxn], vis[Maxn];
int a[Maxn], b[Maxn], id[Maxn];
int n, m, cnt;
inline bool cmp(node x, node y) { return x.b < y.b; }
void init() {
for (int i = 1; i <= n; ++i)
for (int j = 0; j <= m; ++j) f[i][j] = flag[i][j] = 0;
for (int i = 1; i <= n; ++i) s[i] = vis[i] = a[i] = b[i] = id[i] = 0;
cnt = n = m = 0;
}
inline int read() {
int s = 0, w = 1;
char ch = getchar();
while (ch < '0' || ch > '9') {
if (ch == '-') w = -1;
ch = getchar();
}
while (ch >= '0' && ch <= '9')
s = (s << 3) + (s << 1) + (ch ^ 48), ch = getchar();
return s * w;
}
int main() {
int T = read();
while (T--) {
n = read(), m = read();
for (int i = 1; i <= n; ++i) g[i].a = read(), g[i].b = read(), g[i].id = i;
sort(g + 1, g + 1 + n, cmp);
for (int i = 1; i <= n; ++i) a[i] = g[i].a, b[i] = g[i].b, id[i] = g[i].id;
memset(f, 0xcf, sizeof(f));
f[0][0] = 0;
for (int i = 1; i <= n; ++i)
for (int j = 0; j <= min(i, m); ++j) {
f[i][j] = f[i - 1][j] + b[i] * (m - 1), flag[i][j] = 0;
if (j && f[i - 1][j - 1] + a[i] + b[i] * (j - 1) > f[i][j])
f[i][j] = f[i - 1][j - 1] + a[i] + b[i] * (j - 1), flag[i][j] = 1;
}
int i = n, j = m;
while (i) {
if (flag[i][j]) s[++cnt] = i, vis[i] = 1, --j;
--i;
}
printf("%d\n", (n << 1) - m);
for (int i = cnt; i > 1; --i) printf("%d ", id[s[i]]);
for (int i = 1; i <= n; ++i)
if (!vis[i]) printf("%d %d ", id[i], -id[i]);
printf("%d\n", id[s[1]]);
init();
}
return 0;
}
| 12 | CPP |
#include <bits/stdc++.h>
using namespace std;
struct flow {
static const int N = 200005, INF = 1e9;
int n, s, t;
struct edge {
int v, w, f, c, nxt;
} e[N];
int head[N], cur[N], cnt;
void addedge(int u, int v, int w, int f, int c) {
cnt++;
e[cnt].v = v, e[cnt].w = w, e[cnt].f = f, e[cnt].c = c;
e[cnt].nxt = head[u];
head[u] = cnt;
}
void add(int u, int v, int w, int c = 0) {
addedge(u, v, w, w, c);
addedge(v, u, w, 0, -c);
}
void init() {
cnt = 0;
for (int i = 1; i <= n; i++) head[i] = 0;
}
int dep[N], q[N];
int bfs() {
for (int i = 1; i <= n; i++) dep[i] = -1, cur[i] = head[i];
dep[s] = 0;
int l = 0, r = 1;
q[0] = s;
while (l < r) {
int u = q[l++];
for (int i = head[u]; i; i = e[i].nxt) {
if (dep[e[i].v] == -1 && e[i].f > 0) {
dep[e[i].v] = dep[u] + 1;
q[r++] = e[i].v;
}
}
}
return dep[t] != -1;
}
int dfs(int u, int lim) {
if (u == t || lim == 0) return lim;
int flow = 0, f;
for (int i = cur[u]; i; i = e[i].nxt) {
cur[u] = i;
if (dep[e[i].v] == dep[u] + 1 && (f = dfs(e[i].v, min(lim, e[i].f)))) {
flow += f;
lim -= f;
e[i].f -= f;
e[(i - 1 ^ 1) + 1].f += f;
if (!lim) break;
}
}
return flow;
}
int max_flow() {
int mf = 0;
while (bfs()) mf += dfs(s, INF);
return mf;
}
int h[N], dis[N], pre[N], pu[N];
priority_queue<pair<int, int>, vector<pair<int, int>>,
greater<pair<int, int>>>
pq;
int min_cost(int f) {
int res = 0;
for (int i = 1; i <= cnt; i += 2) e[i].f = e[i].w;
for (int i = 2; i <= cnt; i += 2) e[i].f = 0;
while (f > 0) {
for (int i = 1; i <= n; i++) dis[i] = INF;
dis[s] = 0;
pq.emplace(0, s);
while (!pq.empty()) {
auto p = pq.top();
pq.pop();
int u = p.second;
if (dis[u] < p.first) continue;
for (int i = head[u]; i; i = e[i].nxt) {
int v = e[i].v, c = e[i].c, f = e[i].f;
if (f > 0 && dis[v] > dis[u] + c + h[u] - h[v]) {
dis[v] = dis[u] + c + h[u] - h[v];
pre[v] = i, pu[v] = u;
pq.emplace(dis[v], v);
}
}
}
if (dis[t] == INF) return -1;
for (int i = 1; i <= n; i++) h[i] += dis[i];
int d = f;
for (int u = t; u != s; u = pu[u]) d = min(d, e[pre[u]].f);
f -= d;
res += d * h[t];
for (int u = t; u != s; u = pu[u]) {
e[pre[u]].f -= d;
e[(pre[u] - 1 ^ 1) + 1].f += d;
}
}
return res;
}
} g;
const int N = 200;
int n, k, a[N], b[N], x[N], y[N], t;
vector<int> ans;
int main() {
scanf("%d", &t);
while (t--) {
scanf("%d%d", &n, &k);
g.n = 2 * n + 2, g.s = 2 * n + 1, g.t = 2 * n + 2;
g.init();
for (int i = 1; i <= n; i++) {
g.add(g.s, i, 1, 0);
g.add(i + n, g.t, 1, 0);
scanf("%d%d", &a[i], &b[i]);
for (int j = 1; j < k; j++) g.add(i, j + n, 1, -(a[i] + (j - 1) * b[i]));
for (int j = k; j < n; j++) g.add(i, j + n, 1, -((k - 1) * b[i]));
g.add(i, n + n, 1, -(a[i] + (k - 1) * b[i]));
}
g.min_cost(g.max_flow());
for (int i = 1; i <= n; i++) {
for (int j = g.head[i]; j; j = g.e[j].nxt)
if (g.e[j].v != g.s && g.e[j].f == 0) x[i] = g.e[j].v - n;
y[x[i]] = i;
}
ans.clear();
for (int i = 1; i < k; i++)
if (1 <= y[i] && y[i] <= n) ans.push_back(y[i]);
for (int i = k; i < n; i++)
if (1 <= y[i] && y[i] <= n) ans.push_back(y[i]), ans.push_back(-y[i]);
ans.push_back(y[n]);
printf("%d\n", ans.size());
for (auto i : ans) printf("%d ", i);
puts("");
}
return 0;
}
| 12 | CPP |
#include <bits/stdc++.h>
using namespace std;
long long t, n, k;
long long a[80][80], x[80], y[80];
void hungarian() {
vector<long long> u(n + 1), v(n + 1), p(n + 1), way(n + 1);
for (long long i = 1; i <= n; i++) {
p[0] = i;
long long j0 = 0;
vector<long long> minv(n + 1, 1000000000000000000);
vector<char> used(n + 1, false);
do {
used[j0] = true;
long long i0 = p[j0], delta = 1000000000000000000, j1;
for (long long j = 1; j <= n; j++)
if (!used[j]) {
long long cur = a[i0][j] - u[i0] - v[j];
if (cur < minv[j]) minv[j] = cur, way[j] = j0;
if (minv[j] < delta) delta = minv[j], j1 = j;
}
for (long long j = 0; j <= n; j++) {
if (used[j])
u[p[j]] += delta, v[j] -= delta;
else
minv[j] -= delta;
}
j0 = j1;
} while (p[j0] != 0);
do {
long long j1 = way[j0];
p[j0] = p[j1];
j0 = j1;
} while (j0);
}
vector<long long> ans(n + 1), br(n + 1);
for (long long j = 1; j <= n; j++) ans[p[j]] = j;
for (long long i = 1; i <= n; i++) br[ans[i]] = i;
cout << k + (n - k) * 2 << "\n";
for (long long i = 1; i <= n; i++) {
if (i < k)
cout << br[i] << " ";
else if (i > k)
cout << br[i] << " " << -br[i] << " ";
}
cout << br[k] << "\n";
}
signed main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> t;
while (t--) {
cin >> n >> k;
for (long long i = 1; i <= n; i++) cin >> x[i] >> y[i];
for (long long i = 1; i <= n; i++) {
for (long long j = 1; j <= n; j++) {
if (j <= k)
a[i][j] = -(x[i] + (j - 1) * y[i]);
else
a[i][j] = -((k - 1) * y[i]);
}
}
hungarian();
}
}
| 12 | CPP |
#include <bits/stdc++.h>
using namespace std;
struct minion {
int a, b, id;
};
bool sortb(minion x, minion y) { return x.b < y.b; }
int n, k;
minion ar[100];
int dp[100][100];
void calc() {
sort(ar, ar + n, sortb);
for (int i = 0; i <= n; ++i)
for (int j = 0; j <= k; ++j) dp[i][j] = -1e9;
dp[0][0] = ar[0].b * (k - 1);
dp[0][1] = ar[0].a;
for (int i = 1; i < n; ++i) {
dp[i][0] = dp[i - 1][0] + ar[i].b * (k - 1);
for (int j = 1; j <= k; ++j)
dp[i][j] = max(dp[i - 1][j - 1] + ar[i].a + (j - 1) * ar[i].b,
dp[i - 1][j] + ar[i].b * (k - 1));
}
int place = k;
vector<minion> used, notused;
for (int i = n - 1; i > 0; --i) {
if (place == 0 || dp[i][place] == dp[i - 1][place] + ar[i].b * (k - 1))
notused.push_back(ar[i]);
else {
--place;
used.push_back(ar[i]);
}
}
if (place == 1)
used.push_back(ar[0]);
else
notused.push_back(ar[0]);
cout << 2 * n - k << '\n';
for (int i = used.size() - 1; i > 0; --i) cout << used[i].id << " ";
for (auto u : notused) cout << u.id << " -" << u.id << ' ';
cout << used[0].id << '\n';
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int t;
cin >> t;
while (t--) {
cin >> n >> k;
for (int i = 0; i < n; ++i) {
cin >> ar[i].a >> ar[i].b;
ar[i].id = i + 1;
}
calc();
}
}
| 12 | CPP |
#include <bits/stdc++.h>
using namespace std;
template <typename flow_type, typename cost_type>
struct min_cost_max_flow {
struct edge {
size_t src, dst, rev;
flow_type flow, cap;
cost_type cost;
};
int n;
vector<vector<edge>> adj;
min_cost_max_flow(int n) : n(n), adj(n), potential(n), dist(n), back(n) {}
void add_edge(size_t src, size_t dst, flow_type cap, cost_type cost) {
adj[src].push_back({src, dst, adj[dst].size(), 0, cap, cost});
if (src == dst) adj[src].back().rev++;
adj[dst].push_back({dst, src, adj[src].size() - 1, 0, 0, -cost});
}
vector<cost_type> potential;
inline cost_type rcost(const edge &e) {
return e.cost + potential[e.src] - potential[e.dst];
}
void bellman_ford(int source) {
for (int k = 0; k < n; ++k)
for (int u = 0; u < n; ++u)
for (edge &e : adj[u])
if (e.cap > 0 && rcost(e) < 0) potential[e.dst] += rcost(e);
}
const cost_type oo = numeric_limits<cost_type>::max();
vector<cost_type> dist;
vector<edge *> back;
cost_type dijkstra(int source, int sink) {
fill(dist.begin(), dist.end(), oo);
priority_queue<pair<cost_type, int>, vector<pair<cost_type, int>>,
greater<pair<cost_type, int>>>
pq;
for (pq.push({dist[source] = 0, source}); !pq.empty();) {
pair<cost_type, int> p = pq.top();
pq.pop();
if (dist[p.second] < p.first) continue;
if (p.second == sink) break;
for (edge &e : adj[p.second])
if (e.flow < e.cap && dist[e.dst] > dist[e.src] + rcost(e)) {
back[e.dst] = &e;
pq.push({dist[e.dst] = dist[e.src] + rcost(e), e.dst});
}
}
return dist[sink];
}
pair<flow_type, cost_type> max_flow(int source, int sink) {
flow_type flow = 0;
cost_type cost = 0;
for (int u = 0; u < n; ++u)
for (edge &e : adj[u]) e.flow = 0;
potential.assign(n, 0);
dist.assign(n, 0);
back.assign(n, nullptr);
bellman_ford(source);
while (dijkstra(source, sink) < oo) {
for (int u = 0; u < n; ++u)
if (dist[u] < dist[sink]) potential[u] += dist[u] - dist[sink];
flow_type first = numeric_limits<flow_type>::max();
for (edge *e = back[sink]; e; e = back[e->src])
first = min(first, e->cap - e->flow);
for (edge *e = back[sink]; e; e = back[e->src])
e->flow += first, adj[e->dst][e->rev].flow -= first;
flow += first;
cost += first * (potential[sink] - potential[source]);
}
return {flow, cost};
}
};
int ai[105], bi[105];
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int t;
cin >> t;
while (t--) {
long long n, k, a, b;
cin >> n >> k;
min_cost_max_flow<int, int> g(4 + k + n);
g.add_edge(0, n + 1, k, 0);
g.add_edge(0, n + 2, n - k, 0);
for (int i = 0; i < k; i++) g.add_edge(n + 1, n + 4 + i, 1, 0);
for (int i = 0; i < n; i++) {
cin >> a >> b;
ai[i] = a;
bi[i] = b;
g.add_edge(n + 2, i + 1, 1, -((k - 1) * b));
for (int j = 0; j < k; j++)
g.add_edge(n + 4 + j, i + 1, 1, -(a + (j * b)));
g.add_edge(i + 1, n + 3, 1, 0);
}
long long x = -(g.max_flow(0, n + 3).second);
vector<pair<long long, long long>> ks;
set<int> af;
for (int i = 0; i < n; i++) af.insert(i);
for (int i = 0; i < k; i++)
for (auto edge : g.adj[n + 4 + i])
if (edge.flow == 1) {
ks.push_back(
pair<long long, long long>(bi[edge.dst - 1], edge.dst - 1));
af.erase(edge.dst - 1);
}
sort((ks).begin(), (ks).end());
vector<int> res;
for (int i = 0; i < k - 1; i++) res.push_back(ks[i].second + 1);
for (auto y : af) {
res.push_back(y + 1);
res.push_back(-(y + 1));
}
res.push_back(ks[k - 1].second + 1);
cout << (res.size()) << '\n';
for (auto y : res) cout << y << ' ';
cout << '\n';
}
return 0;
}
| 12 | CPP |
#include <bits/stdc++.h>
using namespace std;
const int MX = 100, inf = 1e9;
struct FlowGraph {
struct Edge {
int to;
int flow, cap, cost;
Edge *res;
Edge() : to(0), flow(0), cap(0), cost(0), res(0) {}
Edge(int to, int flow, int cap, int cost)
: to(to), flow(flow), cap(cap), cost(cost), res(0) {}
void addFlow(int f) {
flow += f;
res->flow -= f;
}
};
vector<vector<Edge *>> adj;
vector<int> dis, pos;
int n;
FlowGraph(int n) : n(n), adj(n), dis(n), pos(n) {}
void add(int u, int v, int cap, int cost) {
Edge *x = new Edge(v, 0, cap, cost);
Edge *y = new Edge(u, cap, cap, -cost);
x->res = y;
y->res = x;
adj[u].push_back(x);
adj[v].push_back(y);
}
pair<long long, long long> maxFlowMinCost(int s, int t) {
vector<bool> inQueue(n);
vector<int> dis(n), cap(n);
vector<Edge *> par(n);
long long maxFlow = 0, minCost = 0;
while (1) {
fill(dis.begin(), dis.end(), inf);
fill(par.begin(), par.end(), nullptr);
fill(cap.begin(), cap.end(), 0);
dis[s] = 0;
cap[s] = inf;
queue<int> q;
q.push(s);
while (q.size()) {
int u = q.front();
q.pop();
inQueue[u] = 0;
for (Edge *v : adj[u]) {
if (v->cap > v->flow && dis[v->to] > dis[u] + v->cost) {
dis[v->to] = dis[u] + v->cost;
par[v->to] = v;
cap[v->to] = min(cap[u], v->cap - v->flow);
if (!inQueue[v->to]) {
q.push(v->to);
inQueue[v->to] = 1;
}
}
}
}
if (!par[t]) break;
maxFlow += cap[t];
minCost += cap[t] * dis[t];
for (int u = t; u != s; u = par[u]->res->to) par[u]->addFlow(cap[t]);
}
return {maxFlow, minCost};
}
};
int n, k, a[MX], b[MX], res[MX];
void solve() {
cin >> n >> k;
for (int i = 0; i < n; i++) cin >> a[i] >> b[i];
FlowGraph g(2 * n + 5);
int s = g.n - 1, t = s - 2;
for (int i = 0; i < n; i++) {
g.add(s, i, 1, 0);
for (int j = 0; j < n; j++) {
if (j + 1 == n) {
g.add(i, n + j, 1, -(a[i] + (k - 1) * b[i]));
} else if (j < k - 1) {
g.add(i, n + j, 1, -(a[i] + j * b[i]));
} else {
g.add(i, n + j, 1, -((k - 1) * b[i]));
}
}
}
for (int j = 0; j < n; j++) g.add(n + j, t, 1, 0);
g.maxFlowMinCost(s, t);
for (int i = 0; i < n; i++)
for (auto *e : g.adj[i])
if (e->to >= n && e->flow == e->cap) res[e->to - n] = i;
vector<int> v;
for (int i = 0; i < n; i++) {
v.push_back(res[i] + 1);
if (i < k - 1 || i + 1 == n) continue;
v.push_back(-(res[i] + 1));
}
cout << v.size() << '\n';
for (int r : v) cout << r << " ";
cout << '\n';
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int t;
cin >> t;
while (t--) solve();
return 0;
}
| 12 | CPP |
#include <bits/stdc++.h>
using namespace std;
template <class T>
void splitstr(const string &s, vector<T> &out) {
istringstream in(s);
out.clear();
copy(istream_iterator<T>(in), istream_iterator<T>(), back_inserter(out));
}
template <class T>
T gcd(T a, T b) {
return b ? gcd(b, a % b) : a;
}
static void redirect(int argc, const char **argv) {
ios::sync_with_stdio(false);
cin.tie(NULL);
if (argc > 1) {
static filebuf f;
f.open(argv[1], ios::in);
cin.rdbuf(&f);
if (!cin) {
cerr << "Failed to open '" << argv[1] << "'" << endl;
exit(1);
}
}
if (argc > 2) {
static filebuf f;
f.open(argv[2], ios::out | ios::trunc);
cout.rdbuf(&f);
if (!cout) {
cerr << "Failed to open '" << argv[2] << "'" << endl;
}
}
cin.exceptions(ios::failbit);
}
struct minion {
int a, b;
int idx;
bool operator<(const minion &other) const { return b < other.b; }
};
int main(int argc, const char **argv) {
redirect(argc, argv);
int T;
cin >> T;
for (int cas = 0; cas < T; cas++) {
int N, K;
cin >> N >> K;
vector<minion> m(N);
for (int i = 0; i < N; i++) {
cin >> m[i].a >> m[i].b;
m[i].idx = i + 1;
}
sort(begin(m), end(m));
vector<vector<int> > dp(N + 1, vector<int>(K + 1, INT_MIN / 2));
vector<vector<int> > team(N + 1, vector<int>(K + 1, 0));
dp[0][0] = 0;
for (int i = 0; i < N; i++) {
for (int j = 0; j <= min(i, K); j++)
dp[i + 1][j] = dp[i][j] + m[i].b * (K - 1);
for (int j = 0; j <= min(i, K - 1); j++) {
int score = dp[i][j] + m[i].a + j * m[i].b;
if (score > dp[i + 1][j + 1]) {
dp[i + 1][j + 1] = score;
team[i + 1][j + 1] = 1;
}
}
}
int n = N;
int k = K;
vector<int> in, out;
while (n > 0) {
int t = team[n][k];
n--;
k -= t;
if (t)
in.push_back(m[n].idx);
else
out.push_back(m[n].idx);
}
reverse(begin(in), end(in));
cout << ((long long)(in).size()) + 2 * ((long long)(out).size()) << '\n';
for (int i = 0; i < K - 1; i++) cout << in[i] << ' ';
for (int v : out) cout << v << ' ' << -v << ' ';
cout << in.back() << '\n';
}
return 0;
}
| 12 | CPP |
#include <bits/stdc++.h>
using namespace std;
template <typename T1, typename T2>
string print_iterable(T1 begin_iter, T2 end_iter, int counter) {
bool done_something = false;
stringstream res;
res << "[";
for (; begin_iter != end_iter and counter; ++begin_iter) {
done_something = true;
counter--;
res << *begin_iter << ", ";
}
string str = res.str();
if (done_something) {
str.pop_back();
str.pop_back();
}
str += "]";
return str;
}
vector<int> SortIndex(int size, std::function<bool(int, int)> compare) {
vector<int> ord(size);
for (int i = 0; i < size; i++) ord[i] = i;
sort(ord.begin(), ord.end(), compare);
return ord;
}
template <typename T>
bool MinPlace(T& a, const T& b) {
if (a > b) {
a = b;
return true;
}
return false;
}
template <typename T>
bool MaxPlace(T& a, const T& b) {
if (a < b) {
a = b;
return true;
}
return false;
}
template <typename S, typename T>
ostream& operator<<(ostream& out, const pair<S, T>& p) {
out << "{" << p.first << ", " << p.second << "}";
return out;
}
template <typename T>
ostream& operator<<(ostream& out, const vector<T>& v) {
out << "[";
for (int i = 0; i < (int)v.size(); i++) {
out << v[i];
if (i != (int)v.size() - 1) out << ", ";
}
out << "]";
return out;
}
template <class TH>
void _dbg(const char* name, TH val) {
clog << name << ": " << val << endl;
}
template <class TH, class... TA>
void _dbg(const char* names, TH curr_val, TA... vals) {
while (*names != ',') clog << *names++;
clog << ": " << curr_val << ", ";
_dbg(names + 1, vals...);
}
void solve() {
int N, K;
cin >> N >> K;
vector<int> a(N);
vector<int> b(N);
for (int i = 0; i < N; i++) cin >> a[i] >> b[i];
vector<int> ord = SortIndex(N, [&](int i, int j) { return b[i] < b[j]; });
vector<vector<int>> din(N + 1, vector<int>(N + 1, -1e9));
din[0][0] = 0;
for (int i = 0; i < N; i++) {
int it = ord[i];
din[i + 1][0] = din[i][0] + (K - 1) * b[it];
for (int j = 1; j <= N; j++) {
din[i + 1][j] = max(din[i][j] + (K - 1) * b[it],
din[i][j - 1] + (j - 1) * b[it] + a[it]);
}
}
vector<bool> destroyed(N + 1, false);
int cnt = K;
for (int i = N - 1; i >= 0; i--) {
int it = ord[i];
if (din[i + 1][cnt] == din[i][cnt] + (K - 1) * b[it]) {
destroyed[i] = true;
} else
cnt--;
}
assert(cnt == 0);
vector<int> ans;
int last;
for (int i = 0; i < N; i++) {
if (!destroyed[i]) {
if (((int)((ans).size())) < K - 1)
ans.push_back(ord[i] + 1);
else
last = ord[i];
}
}
for (int i = 0; i < N; i++) {
if (destroyed[i]) {
ans.push_back(ord[i] + 1);
ans.push_back(-ord[i] - 1);
}
}
ans.push_back(last + 1);
cout << ans.size() << "\n";
for (int x : ans) cout << x << " ";
cout << "\n";
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int T;
cin >> T;
for (int t = 0; t < T; t++) solve();
}
| 12 | CPP |
#include <bits/stdc++.h>
using namespace std;
template <typename T>
ostream &operator<<(ostream &os, const vector<T> &v) {
os << '{';
string sep;
for (const auto &x : v) os << sep << x, sep = ", ";
return os << '}';
}
template <typename A, typename B>
ostream &operator<<(ostream &os, const pair<A, B> &p) {
return os << '(' << p.first << ", " << p.second << ')';
}
void dbg_out() { cerr << endl; }
template <typename Head, typename... Tail>
void dbg_out(Head H, Tail... T) {
cerr << ' ' << H;
dbg_out(T...);
}
template <typename T1, typename T2>
bool maximize(T1 &a, const T2 &b) {
if (a < b) {
a = b;
return true;
}
return false;
}
template <typename T>
void output_vector(const vector<T> &v, bool add_one = false, int start = -1,
int end = -1) {
if (start < 0) start = 0;
if (end < 0) end = int(v.size());
for (int i = start; i < end; i++)
cout << v[i] + (add_one ? 1 : 0) << (i < end - 1 ? ' ' : '\n');
}
const int INF = 1e9 + 5;
struct minion {
int A, B, index;
bool operator<(const minion &other) const { return B < other.B; }
};
void run_case() {
int N, K;
cin >> N >> K;
vector<minion> minions(N);
for (minion &m : minions) cin >> m.A >> m.B;
for (int i = 0; i < N; i++) minions[i].index = i + 1;
sort(minions.begin(), minions.end());
vector<int> dp(K + 1, -INF);
dp[0] = 0;
vector<vector<bool>> previous(N + 1, vector<bool>(K + 1, false));
for (int i = 0; i < N; i++) {
vector<int> next_dp(K + 1, -INF);
for (int k = 0; k <= K; k++) {
if (maximize(next_dp[k], dp[k] + (K - 1) * minions[i].B))
previous[i + 1][k] = false;
if (k < K &&
maximize(next_dp[k + 1], dp[k] + minions[i].A + k * minions[i].B))
previous[i + 1][k + 1] = true;
}
dp = next_dp;
};
vector<int> assignment(N, -1);
for (int n = N, k = K, end = N; n > 0; n--)
if (previous[n][k])
assignment[--k] = minions[n - 1].index;
else
assignment[--end] = minions[n - 1].index;
vector<int> solution;
for (int k = 0; k < K - 1; k++) solution.push_back(assignment[k]);
for (int k = K; k < N; k++) {
solution.push_back(assignment[k]);
solution.push_back(-assignment[k]);
}
solution.push_back(assignment[K - 1]);
assert(int(solution.size()) == 2 * N - K);
cout << solution.size() << '\n';
output_vector(solution);
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int tests;
cin >> tests;
while (tests-- > 0) run_case();
}
| 12 | CPP |
#include <bits/stdc++.h>
using namespace std;
const int inf = 0x3f3f3f3f;
struct Edge {
int to, val, next, cost;
} edge[25086];
int s, t;
int cnt = -1;
int head[25086];
queue<int> q;
int d[25086];
int cur[25086];
int inq[25086];
int vis[25086];
int costsum;
void addEdge(int u, int v, int w, int f) {
cnt++;
edge[cnt].to = v;
edge[cnt].val = w;
edge[cnt].next = head[u];
edge[cnt].cost = f;
head[u] = cnt;
cnt++;
edge[cnt].to = u;
edge[cnt].val = 0;
edge[cnt].next = head[v];
edge[cnt].cost = -f;
head[v] = cnt;
}
bool bfs() {
memset(d, 0x3f, sizeof(d));
memset(vis, 0, sizeof(vis));
d[s] = 0;
q.push(s);
inq[s] = 1;
while (!q.empty()) {
int u = q.front();
q.pop();
inq[u] = 0;
for (int i = head[u]; i != -1; i = edge[i].next) {
int v = edge[i].to;
cur[v] = head[v];
int f = edge[i].cost;
if (d[v] > d[u] + f && edge[i].val > 0) {
d[v] = d[u] + f;
if (!inq[v]) {
q.push(v);
inq[v] = 1;
}
}
}
}
return d[t] != inf;
}
int dfs(int u, int flow) {
vis[u] = 1;
int nowflow = 0;
if (u == t) return flow;
for (int i = cur[u]; i != -1; i = edge[i].next) {
cur[u] = i;
int v = edge[i].to;
int w = edge[i].val;
int f = edge[i].cost;
if (d[v] == d[u] + f && w > 0 && !vis[v]) {
int k = dfs(v, min(flow - nowflow, w));
if (k > 0) {
edge[i].val -= k;
edge[i ^ 1].val += k;
nowflow += k;
costsum += f * k;
if (nowflow == flow) break;
}
}
}
vis[u] = 0;
if (!nowflow) d[u] = inf;
return nowflow;
}
int dinic() {
int ans = 0;
while (bfs()) {
ans += dfs(s, inf);
}
return ans;
}
int T;
int n, k, a, b;
int opt[25086];
int main() {
scanf("%d", &T);
while (T--) {
memset(head, -1, sizeof(head)), cnt = -1;
scanf("%d%d", &n, &k);
s = 0, t = 2 * n + 1, costsum = 0;
for (int i = 1; i <= n; i++) {
scanf("%d%d", &a, &b);
addEdge(s, i, 1, 0), addEdge(i + n, t, 1, 0);
for (int j = 1; j <= n; j++) {
if (j < k)
addEdge(i, j + n, 1, -(a + (j - 1) * b));
else if (j < n)
addEdge(i, j + n, 1, -(k - 1) * b);
else
addEdge(i, j + n, 1, -(a + (k - 1) * b));
}
}
dinic();
for (int i = 1; i <= n; i++) {
for (int j = head[i]; j != -1; j = edge[j].next) {
if (!edge[j].val) {
opt[edge[j].to - n] = i;
break;
}
}
}
printf("%d\n", k - 1 + (n - k) * 2 + 1);
for (int i = 1; i <= n; i++) {
if (i < k || i == n)
printf("%d ", opt[i]);
else
printf("%d %d ", opt[i], -opt[i]);
}
puts("");
}
}
| 12 | CPP |
#include <bits/stdc++.h>
using namespace std;
struct Edge {
int from, to, capacity, cost;
Edge(int from, int to, int capacity, int cost)
: from(from), to(to), capacity(capacity), cost(cost){};
};
vector<vector<int>> adj, cost, capacity;
const int INF = 2e9;
void shortest_paths(int n, int v0, vector<int>& d, vector<int>& p) {
d.assign(n, INF);
d[v0] = 0;
vector<bool> inq(n, false);
queue<int> q;
q.push(v0);
p.assign(n, -1);
while (!q.empty()) {
int u = q.front();
q.pop();
inq[u] = false;
for (int v : adj[u]) {
if (capacity[u][v] > 0 && d[v] > d[u] + cost[u][v]) {
d[v] = d[u] + cost[u][v];
p[v] = u;
if (!inq[v]) {
inq[v] = true;
q.push(v);
}
}
}
}
}
int min_cost_flow(int N, vector<Edge>& edges, int s, int t) {
adj.assign(N, vector<int>());
cost.assign(N, vector<int>(N, 0));
capacity.assign(N, vector<int>(N, 0));
for (Edge e : edges) {
adj[e.from].push_back(e.to);
adj[e.to].push_back(e.from);
cost[e.from][e.to] = e.cost;
cost[e.to][e.from] = -e.cost;
capacity[e.from][e.to] = e.capacity;
}
int flow = 0;
int cost = 0;
vector<int> d, p;
while (1) {
shortest_paths(N, s, d, p);
if (d[t] == INF) break;
int f = 2000000000;
int cur = t;
while (cur != s) {
f = min(f, capacity[p[cur]][cur]);
cur = p[cur];
}
flow += f;
cost += f * d[t];
cur = t;
while (cur != s) {
capacity[p[cur]][cur] -= f;
capacity[cur][p[cur]] += f;
cur = p[cur];
}
}
return cost;
}
int ab[76][2];
int main() {
int T;
int i, j;
int n, k;
int s, t;
scanf("%d", &T);
while (T--) {
vector<Edge> edges;
vector<int> res;
scanf("%d %d", &n, &k);
s = n + n, t = n + n + 1;
for (i = 0; i < n; i++) {
scanf("%d %d", &ab[i][0], &ab[i][1]);
}
for (i = 0; i < n; i++) {
edges.emplace_back(s, i, 1, 0);
edges.emplace_back(i + n, t, 1, 0);
}
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
if (i >= k - 1 && i < n - 1)
edges.emplace_back(j, i + n, 1, -(k - 1) * ab[j][1]);
else if (i == n - 1)
edges.emplace_back(j, i + n, 1, -(ab[j][0] + (k - 1) * ab[j][1]));
else
edges.emplace_back(j, i + n, 1, -(ab[j][0] + i * ab[j][1]));
}
}
min_cost_flow(n + n + 2, edges, s, t);
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
if (!capacity[j][i + n]) {
if (i >= k - 1 && i < n - 1) {
res.push_back(j + 1);
res.push_back(-j - 1);
} else
res.push_back(j + 1);
}
}
}
printf("%d\n", 2 * n - k);
for (auto o : res) printf("%d ", o);
printf("\n");
}
}
| 12 | CPP |
#include <bits/stdc++.h>
using namespace std;
using ull = unsigned long long;
using ll = long long;
using ld = long double;
const int mod = 1e9 + 7;
const double pi = acos(-1.0);
const int inf = INT_MAX;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int t;
cin >> t;
while (t--) {
int n, k;
cin >> n >> k;
vector<int> a(n), b(n);
for (int i = 0; i < n; i++) cin >> a[i] >> b[i];
vector<int> ind(n);
iota(ind.begin(), ind.end(), 0);
sort(ind.begin(), ind.end(), [&](int i, int j) { return b[i] < b[j]; });
vector<vector<int>> dp(n, vector<int>(n + 1));
dp[0][0] = (k - 1) * b[ind[0]];
dp[0][1] = a[ind[0]];
for (int i = 1; i < n; i++) {
dp[i][0] = (k - 1) * b[ind[i]] + dp[i - 1][0];
for (int j = 1; j <= i + 1; j++) {
if (j < i + 1) {
dp[i][j] = (k - 1) * b[ind[i]] + dp[i - 1][j];
dp[i][j] =
max(dp[i][j], (j - 1) * b[ind[i]] + a[ind[i]] + dp[i - 1][j - 1]);
} else {
dp[i][j] = (j - 1) * b[ind[i]] + a[ind[i]] + dp[i - 1][j - 1];
}
}
}
vector<int> final;
for (int i = n - 1, j = k; j > 0;) {
if (j < i + 1 && dp[i][j] == (k - 1) * b[ind[i]] + dp[i - 1][j]) {
i--;
} else {
final.push_back(ind[i]);
i--, j--;
}
}
reverse(final.begin(), final.end());
cout << k + 2 * (n - k) << '\n';
for (int i = 0; i < k - 1; i++) {
cout << final[i] + 1 << ' ';
}
for (int i = 0; i < n; i++) {
if (count(final.begin(), final.end(), i) == 0) {
cout << i + 1 << ' ' << -i - 1 << ' ';
}
}
cout << final[k - 1] + 1 << '\n';
}
return 0;
}
| 12 | CPP |
#include <bits/stdc++.h>
using namespace std;
const double PI = acos(-1);
const double eps = 1e-12;
const int inf = 2000000000;
const long long int infLL = (long long int)1e18;
long long int MOD = 1000000007;
int MOD1 = 1000000007;
int MOD2 = 1000000009;
inline bool checkBit(long long int n, long long int i) {
return n & (1LL << i);
}
inline long long int setBit(long long int n, long long int i) {
return n | (1LL << i);
;
}
inline long long int resetBit(long long int n, long long int i) {
return n & (~(1LL << i));
}
int dx[] = {0, 0, +1, -1};
int dy[] = {+1, -1, 0, 0};
inline bool EQ(double a, double b) { return fabs(a - b) < 1e-9; }
inline bool isLeapYear(long long int year) {
return (year % 400 == 0) || (year % 4 == 0 && year % 100 != 0);
}
inline void normal(long long int &a) {
a %= MOD;
(a < 0) && (a += MOD);
}
inline long long int modMul(long long int a, long long int b) {
a %= MOD, b %= MOD;
normal(a), normal(b);
return (a * b) % MOD;
}
inline long long int modAdd(long long int a, long long int b) {
a %= MOD, b %= MOD;
normal(a), normal(b);
return (a + b) % MOD;
}
inline long long int modSub(long long int a, long long int b) {
a %= MOD, b %= MOD;
normal(a), normal(b);
a -= b;
normal(a);
return a;
}
inline long long int modPow(long long int b, long long int p) {
long long int r = 1LL;
while (p) {
if (p & 1) r = modMul(r, b);
b = modMul(b, b);
p >>= 1LL;
}
return r;
}
inline long long int modDiv(long long int a, long long int b) {
return modMul(a, modPow(b, MOD - 2));
}
bool comp(const pair<long long int, pair<long long int, long long int> > &p1,
const pair<long long int, pair<long long int, long long int> > &p2) {
return p1.first > p2.first;
}
bool comp1(const pair<long long int, long long int> &p1,
const pair<long long int, long long int> &p2) {
if (p1.first == p2.first) {
return p1.second > p2.second;
}
return p1.first < p2.first;
}
long long int converter(string a) {
long long int i, mul = 1LL, r, t, ans = 0LL;
if (a.length() == 0) return 0;
for (i = a.length() - 1; i >= 0; i--) {
t = a[i] - '0';
r = t % 10;
ans += (mul * r);
mul = mul * 10;
}
return ans;
}
int msb(unsigned x) {
union {
double a;
int b[2];
};
a = x;
return (b[1] >> 20) - 1023;
}
const int MAX = 78;
long long int t, n, k;
pair<pair<long long int, long long int>, long long int> p[MAX];
long long int dp[MAX][MAX];
vector<long long int> good, bad;
long long int solve(long long int idx, long long int cnt) {
if (idx == n + 1) {
if (cnt != k) return -infLL;
return 0;
}
if (dp[idx][cnt] != -1) return dp[idx][cnt];
long long int ret = -infLL;
if (cnt + 1 <= k) {
ret = max(ret, cnt * p[idx].first.first + p[idx].first.second +
solve(idx + 1, cnt + 1));
}
ret = max(ret, ((k - 1) * p[idx].first.first) + solve(idx + 1, cnt));
return dp[idx][cnt] = ret;
}
void trace(long long int idx, long long int cnt) {
if (idx == n + 1) return;
long long int ret1 = -infLL, ret2 = -infLL;
if (cnt + 1 <= k)
ret1 = cnt * p[idx].first.first + p[idx].first.second +
solve(idx + 1, cnt + 1);
ret2 = ((k - 1) * p[idx].first.first) + solve(idx + 1, cnt);
if (ret1 > ret2) {
trace(idx + 1, cnt + 1);
good.push_back(p[idx].second);
} else {
trace(idx + 1, cnt);
bad.push_back(p[idx].second);
}
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
;
cout.unsetf(ios::floatfield);
cout.precision(20);
cout.setf(ios::fixed, ios::floatfield);
;
cin >> t;
while (t--) {
good.clear();
bad.clear();
long long int maxi = 0, idx;
cin >> n >> k;
for (int i = 1; i <= n; ++i) {
cin >> p[i].first.second >> p[i].first.first;
p[i].second = i;
if (p[i].first.second >= maxi) maxi = p[i].first.second, idx = i;
}
if (k == 1) {
cout << 1 << '\n';
cout << idx << '\n';
continue;
}
sort(p + 1, p + n + 1);
for (int i = 1; i <= n; ++i) {
;
}
memset(dp, -1, sizeof(dp));
long long int now = solve(1, 0);
;
trace(1, 0);
reverse((good).begin(), (good).end());
reverse((bad).begin(), (bad).end());
if (good.size() == 0) {
string ss = "";
ss += to_string(n);
ss += '#';
ss += to_string(k);
ss += '#';
for (int i = 1; i <= n; ++i) {
ss += to_string(p[i].first.first);
ss += '#';
ss += to_string(p[i].first.second);
ss += '&';
}
cout << ss << '\n';
continue;
}
cout << good.size() + (2 * bad.size()) << '\n';
for (int i = 0; i < (int)good.size() - 1; ++i) {
cout << good[i] << " ";
}
for (int i = 0; i < bad.size(); ++i) {
cout << bad[i] << " " << -1 * bad[i] << " ";
}
cout << good[good.size() - 1] << '\n';
}
return 0;
}
| 12 | CPP |
#include <bits/stdc++.h>
using namespace std;
const int N = 80;
struct minion {
int a, b, ind;
bool operator<(const minion &other) const { return b < other.b; }
} minions[N];
int n, k;
int memo[N][N], vis[N][N], vid;
int solve(int i, int cnt) {
if (i == n) return cnt == k ? 0 : -1e9;
int &ret = memo[i][cnt];
if (vis[i][cnt] == vid) return ret;
vis[i][cnt] = vid;
ret = solve(i + 1, cnt) + minions[i].b * (k - 1);
if (cnt < k)
ret = max(ret, solve(i + 1, cnt + 1) + minions[i].a + minions[i].b * cnt);
return ret;
}
vector<int> keep, dest;
void path(int i, int cnt) {
if (i == n) return;
if (solve(i + 1, cnt) + minions[i].b * (k - 1) == solve(i, cnt)) {
dest.push_back(minions[i].ind);
return path(i + 1, cnt);
}
keep.push_back(minions[i].ind);
path(i + 1, cnt + 1);
}
void run() {
cin >> n >> k;
for (int i = 0; i < n; i++) {
cin >> minions[i].a >> minions[i].b;
minions[i].ind = i + 1;
}
sort(minions, minions + n);
++vid;
keep.clear();
dest.clear();
path(0, 0);
cout << keep.size() + dest.size() * 2 << '\n';
for (int i = 0; i + 1 < keep.size(); i++) cout << keep[i] << ' ';
for (int x : dest) cout << x << ' ' << -x << ' ';
cout << keep.back() << '\n';
}
int main() {
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
int t;
cin >> t;
while (t--) run();
}
| 12 | CPP |
#include <bits/stdc++.h>
using namespace std;
const int mod = 998244353;
const int inf = 1e9;
const int N = 5005;
const int mf[] = {0, 0, 1, -1}, mc[] = {1, -1, 0, 0};
const double eps = 1e-9;
const double pi = acos(-1);
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int t;
cin >> t;
while (t--) {
int n, k;
cin >> n >> k;
vector<pair<pair<int, int>, int>> v(n);
for (int i = 0; i < n; i++) {
cin >> v[i].first.first >> v[i].first.second;
v[i].second = i + 1;
}
sort((v).begin(), (v).end(),
[&](pair<pair<int, int>, int> i, pair<pair<int, int>, int> j) {
return i.first.second < j.first.second;
});
vector<vector<int>> dp(n + 1, vector<int>(k + 1, -inf));
dp[0][0] = 0;
for (int i = 1; i <= n; i++) {
int a = v[i - 1].first.first;
int b = v[i - 1].first.second;
dp[i][0] = dp[i - 1][0] + (k - 1) * b;
for (int j = 1; j <= k; j++)
dp[i][j] =
max(dp[i - 1][j] + (k - 1) * b, dp[i - 1][j - 1] + a + (j - 1) * b);
}
vector<bool> mark(n + 1);
vector<int> stay;
int j = k;
for (int i = n; i >= 1; i--) {
int a = v[i - 1].first.first;
int b = v[i - 1].first.second;
int id = v[i - 1].second;
if (dp[i][j] == dp[i - 1][j - 1] + a + (j - 1) * b) {
mark[id] = true;
stay.push_back(id);
j--;
}
}
vector<int> ans;
for (int i = k - 1; i > 0; i--) ans.push_back(stay[i]);
for (int i = 1; i <= n; i++)
if (!mark[i]) {
ans.push_back(i);
ans.push_back(-i);
}
ans.push_back(stay[0]);
cout << k + 2 * (n - k) << '\n';
for (int &i : ans) cout << i << " \n"[&i == &ans.back()];
}
return 0;
}
| 12 | CPP |
#include <bits/stdc++.h>
using namespace std;
const pair<long long, long long> IMPOSSIBLE =
make_pair(-999999999999999999, -1);
class Minion {
public:
long long a, b;
int minionId;
bool operator<(const Minion& that) const { return b < that.b; }
Minion(int ma, int mb, int mid) : a(ma), b(mb), minionId(mid) {}
Minion() {}
};
vector<int> getMaximumPowerSequence(int n, int k, vector<Minion> minions) {
sort(minions.begin(), minions.end());
pair<long long, long long> dp[n + 2][k + 1];
for (int i = 0; i <= k; i++) dp[n + 1][i] = IMPOSSIBLE;
dp[n + 1][0] = make_pair(0, -1);
for (int oi = 0; oi < n; oi++) {
pair<long long, long long>* olddp = dp[n + 1];
if (oi > 0) olddp = dp[oi - 1];
pair<long long, long long>* newdp = dp[oi];
for (int i = 0; i <= k; i++) newdp[i] = IMPOSSIBLE;
long long NOT_CHOSEN_BONUS = (long long)(k - 1) * minions[oi].b;
for (int i = 0; i <= k; i++) {
newdp[i] = max(newdp[i], make_pair(olddp[i].first + NOT_CHOSEN_BONUS,
olddp[i].second));
if (i + 1 <= k) {
long long CHOSEN_BONUS = minions[oi].b * i + minions[oi].a;
newdp[i + 1] =
max(newdp[i + 1],
make_pair(olddp[i].first + CHOSEN_BONUS, (long long)oi));
}
}
}
int currentStanding = n - 1;
int toSelect = k;
stack<int> selectedMinion;
vector<bool> isSelected(n + 1, false);
while (toSelect > 0) {
int nextOffer = dp[currentStanding][toSelect].second;
selectedMinion.push(minions[nextOffer].minionId);
isSelected[minions[nextOffer].minionId] = true;
currentStanding = nextOffer - 1;
toSelect--;
}
vector<int> ans;
while (selectedMinion.size() > 1) {
int cm = selectedMinion.top();
selectedMinion.pop();
ans.push_back(cm);
}
for (int i = 1; i <= n; i++) {
if (!isSelected[i]) {
ans.push_back(i);
ans.push_back(-i);
}
}
while (selectedMinion.size() > 0) {
int cm = selectedMinion.top();
selectedMinion.pop();
ans.push_back(cm);
}
return ans;
}
int main() {
int tc;
scanf("%d", &tc);
while (tc--) {
int n, k;
scanf("%d%d", &n, &k);
vector<Minion> minions;
for (int i = 1; i <= n; i++) {
int a, b;
scanf("%d%d", &a, &b);
minions.push_back(Minion(a, b, i));
}
vector<int> answer_sequence = getMaximumPowerSequence(n, k, minions);
printf("%d\n", answer_sequence.size());
for (int v : answer_sequence) printf("%d ", v);
printf("\n");
}
return 0;
}
| 12 | CPP |
#include <bits/stdc++.h>
using namespace std;
template <typename T>
T &read(T &x) {
x = 0;
bool f = 0;
char ch = getchar();
while (ch < '0' || ch > '9') {
if (ch == '-') {
f = 1;
}
ch = getchar();
}
while (ch >= '0' && ch <= '9') {
x = (x << 1) + (x << 3) + (ch ^ 48);
ch = getchar();
}
if (f) {
x = -x;
}
return x;
}
const double eps = 1e-8;
inline int sgn(double x) {
if (x < -eps) {
return -1;
}
return x > eps;
}
void fp() {
freopen(".in", "r", stdin);
freopen(".out", "w", stdout);
}
struct pai {
int a, b, num;
} c[80];
inline bool cmp(pai a, pai b) { return a.b < b.b; }
int f[80][80], g[80][80], ans1[155], ans2[155];
int main() {
int t = read(t);
while (t--) {
int n = read(n), k = read(k), i, j;
for (i = 1; i <= n; i++) {
read(c[i].a);
read(c[i].b);
c[i].num = i;
}
sort(c + 1, c + n + 1, cmp);
for (i = 1; i <= n; i++) {
for (j = 0; j <= min(k, i); j++) {
if (j == i) {
f[i][j] = f[i - 1][j - 1] + c[i].a + c[i].b * (j - 1);
g[i][j] = 2;
continue;
}
if (!j) {
f[i][j] = f[i - 1][j] + c[i].b * (k - 1);
g[i][j] = 1;
continue;
}
if (f[i - 1][j - 1] + c[i].a + c[i].b * (j - 1) <
f[i - 1][j] + c[i].b * (k - 1)) {
f[i][j] = f[i - 1][j] + c[i].b * (k - 1);
g[i][j] = 1;
} else {
f[i][j] = f[i - 1][j - 1] + c[i].a + c[i].b * (j - 1);
g[i][j] = 2;
}
}
}
printf("%d\n", 2 * n - k);
int nowx = n, nowy = k, cnt1 = 0, cnt2 = 0;
for (i = 1; i <= n; i++) {
if (g[nowx][nowy] == 1) {
ans1[++cnt1] = -c[nowx].num;
ans1[++cnt1] = c[nowx].num;
nowx--;
} else {
nowx--;
nowy--;
}
}
nowx = n;
nowy = k;
for (i = 1; i <= n; i++) {
if (g[nowx][nowy] == 1) {
nowx--;
} else {
ans2[++cnt2] = c[nowx].num;
nowx--;
nowy--;
}
}
for (i = cnt2; i >= 2; i--) {
printf("%d ", ans2[i]);
}
for (i = cnt1; i; i--) {
printf("%d ", ans1[i]);
}
printf("%d ", ans2[1]);
puts("");
}
return 0;
}
| 12 | CPP |
#include <bits/stdc++.h>
#pragma GCC optimize("O3")
#pragma GCC target("sse4")
using namespace std;
const double PI = acos(-1.0);
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
long long MinCostMatching(const vector<vector<long long>> &cost,
vector<long long> &Lmate, vector<long long> &Rmate) {
long long n = (long long)(cost.size());
vector<long long> u(n);
vector<long long> v(n);
for (long long i = 0; i < n; i++) {
u[i] = cost[i][0];
for (long long j = 1; j < n; j++) {
u[i] = min(u[i], cost[i][j]);
}
}
for (long long j = 0; j < n; j++) {
v[j] = cost[0][j] - u[0];
for (long long i = 1; i < n; i++) {
v[j] = min(v[j], cost[i][j] - u[i]);
}
}
Lmate = vector<long long>(n, -1);
Rmate = vector<long long>(n, -1);
long long mated = 0;
for (long long i = 0; i < n; i++) {
for (long long j = 0; j < n; j++) {
if (Rmate[j] != -1) {
continue;
}
if (abs(cost[i][j] - u[i] - v[j]) == 0) {
Lmate[i] = j;
Rmate[j] = i;
mated++;
break;
}
}
}
vector<long long> dist(n);
vector<long long> dad(n);
vector<long long> seen(n);
while (mated < n) {
long long s = 0;
while (Lmate[s] != -1) {
s++;
}
fill(dad.begin(), dad.end(), -1);
fill(seen.begin(), seen.end(), 0);
for (long long k = 0; k < n; k++) {
dist[k] = cost[s][k] - u[s] - v[k];
}
long long j = 0;
while (true) {
j = -1;
for (long long k = 0; k < n; k++) {
if (seen[k]) {
continue;
}
if (j == -1 || dist[k] < dist[j]) {
j = k;
}
}
seen[j] = 1;
if (Rmate[j] == -1) {
break;
}
const long long i = Rmate[j];
for (long long k = 0; k < n; k++) {
if (seen[k]) {
continue;
}
const long long new_dist = dist[j] + cost[i][k] - u[i] - v[k];
if (dist[k] > new_dist) {
dist[k] = new_dist;
dad[k] = j;
}
}
}
for (long long k = 0; k < n; k++) {
if (k == j || !seen[k]) {
continue;
}
const long long i = Rmate[k];
v[k] += dist[k] - dist[j];
u[i] -= dist[k] - dist[j];
}
u[s] += dist[j];
while (dad[j] >= 0) {
const long long d = dad[j];
Rmate[j] = Rmate[d];
Lmate[Rmate[j]] = j;
j = d;
}
Rmate[j] = s;
Lmate[s] = j;
mated++;
}
long long value = 0;
for (long long i = 0; i < n; i++) {
value += cost[i][Lmate[i]];
}
return value;
}
int32_t main() {
ios::sync_with_stdio(0);
cin.tie(0);
long long t;
cin >> t;
while (t--) {
long long n, k;
cin >> n >> k;
long long a[n + 5], b[n + 5];
for (long long i = 0; i < n; i++) {
cin >> a[i] >> b[i];
}
vector<vector<long long>> mat(n, vector<long long>(n, 0));
for (long long i = 0; i < (k - 1); i++) {
for (long long j = 0; j < n; j++) {
long long pft = a[j] + min(i, k - 1) * b[j];
mat[i][j] = -pft;
}
}
for (long long i = k - 1; i < n - 1; i++) {
for (long long j = 0; j < n; j++) {
long long pft = min(i, k - 1) * b[j];
mat[i][j] = -pft;
}
}
for (long long j = 0; j < n; j++) {
long long i = n - 1;
long long pft = a[j] + min(i, k - 1) * b[j];
mat[i][j] = -pft;
}
vector<long long> l, r;
long long pft = -MinCostMatching(mat, l, r);
cerr << "pft"
<< "=" << pft << "\n";
cout << k + 2 * (n - k) << "\n";
for (long long i = 0; i < k - 1; i++) {
cout << l[i] + 1 << " ";
}
for (long long i = k - 1; i < n - 1; i++) {
cout << l[i] + 1 << " ";
cout << -l[i] - 1 << " ";
}
cout << l[n - 1] + 1 << " ";
cout << "\n";
}
}
| 12 | CPP |
#include <bits/stdc++.h>
#pragma GCC optimize(3, "Ofast", "inline")
#pragma GCC target("avx")
using namespace std;
inline char gc() {
static char buf[1 << 16], *p1 = buf, *p2 = buf;
if (p1 == p2) {
p2 = (p1 = buf) + fread(buf, 1, 1 << 16, stdin);
if (p2 == p1) return EOF;
}
return *p1++;
}
template <class t>
inline t read(t &x) {
char c = gc();
bool f = 0;
x = 0;
while (!isdigit(c)) f |= c == '-', c = gc();
while (isdigit(c)) x = (x << 1) + (x << 3) + (c ^ 48), c = gc();
if (f) x = -x;
return x;
}
template <class t>
inline void write(t x) {
if (x < 0)
putchar('-'), write(-x);
else {
if (x > 9) write(x / 10);
putchar('0' + x % 10);
}
}
const int N = 205, M = 1e4 + 5, P = 80;
int en = 1, mc, mf, h[N], dis[N], n, k, ans[P];
bool v[N];
struct edge {
int n, v, f, w;
} e[M << 1];
struct fafafa {
int fa, id;
} pre[N];
void add(int x, int y, int f, int w) {
e[++en] = (edge){h[x], y, f, w};
h[x] = en;
}
bool spfa(int s, int t) {
memset(v, 0, sizeof v);
memset(pre, 0, sizeof pre);
memset(dis, 0x3f, sizeof dis);
queue<int> q;
q.push(s);
v[s] = 1;
dis[s] = 0;
while (!q.empty()) {
int x = q.front();
q.pop();
for (int i = h[x]; i; i = e[i].n) {
int y = e[i].v;
if (e[i].f && dis[x] + e[i].w < dis[y]) {
dis[y] = dis[x] + e[i].w;
pre[y] = (fafafa){x, i};
if (!v[y]) {
v[y] = 1;
q.push(y);
}
}
}
v[x] = 0;
}
return dis[t] ^ 0x3f3f3f3f;
}
void mcmf(int s, int t) {
while (spfa(s, t)) {
int flow = INT_MAX;
for (int i = t; i ^ s; i = pre[i].fa) flow = min(flow, e[pre[i].id].f);
for (int i = t; i ^ s; i = pre[i].fa) {
e[pre[i].id].f -= flow;
e[pre[i].id ^ 1].f += flow;
}
mf += flow;
mc += flow * dis[t];
}
}
void exadd(int x, int y, int f, int w) {
add(x, y, f, w);
add(y, x, 0, -w);
}
void doit() {
read(n);
read(k);
for (int i = 1; i <= n; i++) exadd(0, i, 1, 0), exadd(i + n, n * 2 + 1, 1, 0);
for (int i = 1, a, b; i <= n; i++) {
read(a);
read(b);
for (int j = 1, val; j <= n; j++) {
if (j < k)
val = a + (j - 1) * b;
else if (j < n)
val = (k - 1) * b;
else
val = a + (k - 1) * b;
exadd(i, j + n, 1, -val);
}
}
mcmf(0, n * 2 + 1);
write(k + (n - k) * 2);
puts("");
for (int x = 1; x <= n; x++)
for (int i = h[x]; i; i = e[i].n) {
int y = e[i].v;
if (y <= n) continue;
if (!e[i].f) ans[y - n] = x;
}
for (int i = 1; i <= n; i++) {
write(ans[i]);
putchar(' ');
if (i >= k && i < n) write(-ans[i]), putchar(' ');
}
puts("");
en = 1;
mc = mf = 0;
for (int i = 0; i <= n * 2 + 1; i++) h[i] = 0;
}
signed main() {
int t;
read(t);
while (t--) doit();
}
| 12 | CPP |
#include <bits/stdc++.h>
using namespace std;
template <typename T>
inline void read(T &x) {
static char _c;
static bool _f;
x = 0;
_f = 0;
_c = getchar();
while (_c < '0' || '9' < _c) {
if (_c == '-') _f = true;
_c = getchar();
}
while ('0' <= _c && _c <= '9') {
x = (x << 1) + (x << 3) + (_c & 15);
_c = getchar();
}
if (_f) x = -x;
}
template <typename T, typename... Args>
inline void read(T &x, Args &...args) {
read(x);
read(args...);
}
template <typename T>
inline void Min(T &x, T y) {
if (y < x) x = y;
}
template <typename T>
inline void Max(T &x, T y) {
if (x < y) x = y;
}
const int INF = 0x3f3f3f3f;
const long long LINF = 0x3f3f3f3f3f3f3f3f;
const double pi = (double)acos(-1.0);
const double eps = (double)1e-8;
const int e5 = (int)1e5 + 5;
const int MOD = (int)1000000007;
template <typename T0, typename T1>
inline void depair(T0 &x, T1 &y, pair<T0, T1> &p) {
x = p.first, y = p.second;
}
inline int sig(double x) { return x < -eps ? -1 : eps < x; }
long long fp(long long a, long long n, long long mod = MOD) {
if (n < 0) a = fp(a, mod - 2, mod), n = -n;
long long res = 1;
for (; n; n >>= 1, a = a * a % mod)
if (n & 1) res = res * a % mod;
return res;
}
struct Mint {
int x;
Mint() { x = 0; }
Mint(int _x) : x(_x) {
if (x < 0 || x >= MOD) x = (x % MOD + MOD) % MOD;
}
Mint(long long _x) : x(_x) {
if (x < 0 || x >= MOD) x = (x % MOD + MOD) % MOD;
}
Mint operator-() const { return Mint(MOD - x); }
Mint operator+(const Mint &rhs) const {
return Mint(x + rhs.x >= MOD ? x + rhs.x - MOD : x + rhs.x);
}
Mint operator-(const Mint &rhs) const {
return Mint(x - rhs.x < 0 ? x - rhs.x + MOD : x - rhs.x);
}
Mint operator*(const Mint &rhs) const {
return Mint((long long)x * rhs.x % MOD);
}
Mint operator/(const Mint &rhs) const {
return Mint(x * fp(rhs.x, -1) % MOD);
}
Mint &operator+=(const Mint &rhs) {
x += rhs.x;
if (x >= MOD) x -= MOD;
return *this;
}
Mint &operator*=(const Mint &rhs) {
x = ((long long)x * rhs.x) % MOD;
return *this;
}
bool operator==(const Mint &rhs) const { return x == rhs.x; }
bool operator!=(const Mint &rhs) const { return x != rhs.x; }
friend ostream &operator<<(ostream &out, const Mint &rhs) {
return out << rhs.x;
}
friend istream &operator>>(istream &in, Mint &rhs) { return in >> rhs.x; }
};
const int maxn = (int)2e5 + 20;
const int maxm = (int)1e6 + 20;
void work() {
int n, k;
cin >> n >> k;
vector<tuple<int, int, int> > a(n);
for (int i = 0; i < n; i++) {
int x, y;
cin >> x >> y;
a[i] = make_tuple(x, y, i);
}
sort(a.begin(), a.end(),
[](tuple<int, int, int> lhs, tuple<int, int, int> rhs) {
return get<1>(lhs) < get<1>(rhs);
});
vector<vector<int> > dp(n + 1, vector<int>(k + 1, -INF));
dp[0][0] = 0;
for (int i = 0; i < n; i++) {
int x, y, id;
tie(x, y, id) = a[i];
for (int j = 0; j <= k; j++) {
Max(dp[i + 1][j], dp[i][j] + (k - 1) * y);
if (j != k) Max(dp[i + 1][j + 1], dp[i][j] + x + j * y);
}
}
vector<int> sta(n, -1);
int ni = n, nj = k;
int cnt = k;
while (ni) {
int x, y, id;
tie(x, y, id) = a[ni - 1];
if (nj && dp[ni - 1][nj - 1] + (nj - 1) * y + x == dp[ni][nj]) {
sta[id] = cnt--;
nj--;
}
ni--;
}
vector<int> opt;
for (int i = 1; i <= k; i++) {
if (i == k) {
for (int j = 0; j < n; j++)
if (sta[j] == -1) opt.push_back(j + 1), opt.push_back(-j - 1);
}
for (int j = 0; j < n; j++)
if (sta[j] == i) opt.push_back(j + 1);
}
cout << opt.size() << endl;
for (int i = 0; i < opt.size(); i++) {
cout << opt[i];
if (i != opt.size() - 1) cout << " ";
}
cout << endl;
}
int main(int argc, char **argv) {
int tc = 1;
read(tc);
for (int ca = 1; ca <= tc; ca++) {
work();
}
return 0;
}
| 12 | CPP |
#include <bits/stdc++.h>
#pragma GCC optimize("Ofast, unroll-loops", "omit-frame-pointer", "inline")
#pragma GCC option("arch=native", "tune=native", "no-zero-upper")
#pragma GCC target( \
"sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native,avx2")
using namespace std;
using ll = long long;
using ull = unsigned long long;
using ld = long double;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
int getrnd(int l, int r) { return uniform_int_distribution<int>(l, r)(rng); }
ll getrndll(ll l, ll r) { return uniform_int_distribution<ll>(l, r)(rng); }
template <typename T1, typename T2>
inline bool relax(T1& a, const T2& b) {
if (a > b) {
a = b;
return 1;
}
return 0;
}
template <typename T1, typename T2>
inline bool strain(T1& a, const T2& b) {
if (a < b) {
a = b;
return 1;
}
return 0;
}
void solve() {
int n, k;
cin >> n >> k;
vector<pair<int, pair<int, int>>> a(n);
for (int i = 0; i < n; ++i)
cin >> a[i].second.first >> a[i].first, a[i].second.second = i;
sort(a.begin(), a.end());
vector<int> dp(k + 1, -1e9);
vector<vector<int>> from(n, vector<int>(k + 1));
dp[0] = 0;
for (int i = 0; i < n; ++i) {
vector<int> ndp(k + 1, -1e9);
for (int j = 0; j <= min(i, k); ++j) {
if (strain(ndp[j], dp[j] + (k - 1) * a[i].first)) from[i][j] = 0;
if (j + 1 <= k &&
strain(ndp[j + 1], dp[j] + a[i].second.first + a[i].first * j))
from[i][j + 1] = 1;
}
dp.swap(ndp);
}
int cur = k;
vector<int> have;
for (int i = n - 1; i >= 0; --i) {
if (from[i][cur]) {
have.push_back(a[i].second.second);
--cur;
}
}
assert(cur == 0);
reverse(have.begin(), have.end());
vector<int> ans;
for (int i = 0; i < k - 1; ++i) ans.push_back(have[i] + 1);
for (int i = 0; i < n; ++i)
if (count(have.begin(), have.end(), i) == 0)
ans.push_back(i + 1), ans.push_back(-(i + 1));
ans.push_back(have.back() + 1);
cout << ans.size() << '\n';
for (int x : ans) cout << x << ' ';
cout << '\n';
}
int main() {
ios::sync_with_stdio(0);
cin.tie(nullptr);
cout.tie(nullptr);
srand(time(0));
int t = 1;
cin >> t;
while (t--) solve();
return 0;
}
| 12 | CPP |
#include <bits/stdc++.h>
using namespace std;
template <typename T>
void __read(T &a) {
cin >> a;
}
template <typename T, typename... Args>
void __read(T &a, Args &...args) {
cin >> a;
__read(args...);
}
constexpr long long M7 = 1000000007ll;
constexpr long long M9 = 1000000009ll;
constexpr long long MFFT = 998244353ll;
template <class T>
void outv(T &a) {
for (auto &x : a) cout << x << ' ';
}
static mt19937 rnd(static_cast<unsigned>(
chrono::steady_clock::now().time_since_epoch().count()));
auto __fast_io__ = (ios_base::sync_with_stdio(false), cin.tie(nullptr));
int32_t main() {
int t;
__read(t);
while (t--) {
int n, k;
__read(n, k);
vector<pair<int, int>> a(n);
for (auto &[l, r] : a) {
cin >> l >> r;
}
vector<int> ind(n);
iota((ind).begin(), (ind).end(), 0);
sort((ind).begin(), (ind).end(),
[&](int i, int j) { return a[i].second < a[j].second; });
vector<vector<int>> dp(n + 1, vector<int>(k + 1, -1));
vector<vector<int>> pr(n + 1, vector<int>(k + 1, -1));
dp[0][0] = 0;
for (int i = 0; i < n; ++i) {
auto &[l, r] = a[ind[i]];
for (int j = 0; j <= k; ++j) {
if (dp[i][j] == -1) {
continue;
}
if (j + 1 <= k) {
if (dp[i + 1][j + 1] < dp[i][j] + l + r * j) {
dp[i + 1][j + 1] = dp[i][j] + l + r * j;
pr[i + 1][j + 1] = j;
}
}
if (dp[i + 1][j] < dp[i][j] + r * (k - 1)) {
dp[i + 1][j] = dp[i][j] + r * (k - 1);
pr[i + 1][j] = j;
}
}
}
vector<int> g, b;
int j = k;
for (int i = n - 1; i >= 0; --i) {
if (pr[i + 1][j] == j) {
b.push_back(ind[i]);
} else {
g.push_back(ind[i]);
}
j = pr[i + 1][j];
}
reverse((g).begin(), (g).end());
reverse((b).begin(), (b).end());
cout << b.size() * 2 + g.size() << '\n';
for (int i = 0; i + 1 < g.size(); ++i) {
cout << g[i] + 1 << ' ';
}
for (auto &i : b) {
cout << i + 1 << ' ' << -(i + 1) << ' ';
}
cout << g.back() + 1 << '\n';
}
return 0;
}
| 12 | CPP |
#include <bits/stdc++.h>
using namespace std;
using uint = unsigned int;
using ll = long long;
using ld = long double;
using ull = unsigned long long;
using pii = pair<int, int>;
using pll = pair<ll, ll>;
void debug_out() { cerr << endl; }
template <typename Head, typename... Tail>
void debug_out(Head H, Tail... T) {
cerr << " " << H;
debug_out(T...);
}
template <typename T1, typename T2>
ostream &operator<<(ostream &out, const pair<T1, T2> &item) {
out << '(' << item.first << ", " << item.second << ')';
return out;
}
template <typename T>
ostream &operator<<(ostream &out, const vector<T> &v) {
for (const auto &item : v) out << item << ' ';
return out;
}
const int N = 80;
struct Minion {
int id, a, b;
bool operator<(const Minion &o) const { return b < o.b; }
};
ll s[N];
bool ok[N];
int prv[N][N];
ll dp[N][N];
Minion v[N];
int main() {
ios_base::sync_with_stdio(false);
int t, n, k;
for (cin >> t; t; --t) {
cin >> n >> k;
for (int i = 1; i <= n; ++i) cin >> v[i].a >> v[i].b, v[i].id = i;
sort(v + 1, v + n + 1);
for (int i = 1; i <= n; ++i) s[i] = s[i - 1] + v[i].b;
memset(dp, -1, sizeof dp);
dp[0][0] = 0;
int lst = -1;
ll ans = 0;
for (int i = 1; i <= n; ++i)
for (int nr = 1; nr <= i && nr <= k; ++nr) {
for (int j = 0; j < i; ++j) {
if (dp[j][nr - 1] < 0) continue;
ll val = dp[j][nr - 1] + v[i].a + 1LL * v[i].b * (nr - 1) +
1LL * (s[i - 1] - s[j]) * (k - 1);
if (val > dp[i][nr]) dp[i][nr] = val, prv[i][nr] = j;
}
if (dp[i][k] >= 0) {
ll val = dp[i][k] + 1LL * (s[n] - s[i]) * (k - 1);
if (val > ans) ans = val, lst = i;
}
}
memset(ok, 0, sizeof ok);
for (int i = lst, nr = k; nr; i = prv[i][nr], --nr) ok[i] = true;
cout << 2 * n - k << '\n';
for (int i = 1, nr = 0; nr < k - 1; ++i)
if (ok[i]) cout << v[i].id << ' ', ++nr;
for (int i = 1; i <= n; ++i)
if (!ok[i]) cout << v[i].id << ' ' << -v[i].id << ' ';
cout << v[lst].id << '\n';
}
return 0;
}
| 12 | CPP |
#include <bits/stdc++.h>
using namespace std;
const int INF = 2e9;
int g[80][80];
int n, k, a[80], b[80];
int job[80];
int u[80], v[80];
bool used[80];
int dist[80];
int par[80];
void hungarian() {
for (int i = 1; i <= n; i++) {
job[0] = i;
int j0 = 0;
for (int l = 0; l < 80; l++) {
used[l] = 0;
dist[l] = INF;
par[l] = 79;
}
while (job[j0]) {
used[j0] = 1;
int i0 = job[j0], d = INF, j1 = 79;
for (int j = 1; j <= n; j++) {
if (used[j]) continue;
int w = g[i0][j] - u[i0] - v[j];
if (w < dist[j]) {
dist[j] = w;
par[j] = j0;
}
if (dist[j] < d) {
d = dist[j];
j1 = j;
}
}
for (int j = 0; j <= n; j++) {
if (used[j]) {
u[job[j]] += d;
v[j] -= d;
} else
dist[j] -= d;
}
j0 = j1;
}
while (j0) {
int j1 = par[j0];
job[j0] = job[j1];
j0 = j1;
}
}
}
void solve() {
memset(g, 0, sizeof(g));
memset(u, 0, sizeof(u));
memset(v, 0, sizeof(v));
memset(job, 0, sizeof(job));
cin >> n >> k;
for (int i = 1; i <= n; i++) {
cin >> a[i] >> b[i];
}
for (int i = 1; i <= n; i++) {
g[1][i] = a[i] + b[i] * (k - 1);
for (int j = 2; j <= k; j++) {
g[j][i] = a[i] + (j - 2) * b[i];
}
for (int j = k + 1; j <= n; j++) {
g[j][i] = b[i] * (k - 1);
}
}
for (int i1 = 1; i1 <= n; i1++)
for (int i2 = 1; i2 <= n; i2++) {
g[i1][i2] = -g[i1][i2];
}
hungarian();
vector<int> ans;
for (int idx = 2; idx <= k; idx++) {
for (int i = 1; i <= n; i++) {
if (job[i] == idx) ans.push_back(i);
}
}
for (int idx = k + 1; idx <= n; idx++) {
for (int i = 1; i <= n; i++) {
if (job[i] == idx) {
ans.push_back(i);
ans.push_back(-i);
}
}
}
for (int i = 1; i <= n; i++) {
if (job[i] == 1) {
ans.push_back(i);
}
}
cout << ans.size() << endl;
for (auto xd : ans) cout << xd << " ";
cout << endl;
}
int main() {
int t;
cin >> t;
while (t--) solve();
return 0;
}
| 12 | CPP |
#include <bits/stdc++.h>
using namespace std;
template <typename T>
using minpq = priority_queue<T, vector<T>, greater<T>>;
int n, k, a, b;
long long t;
vector<long long> ve[2][2];
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cin >> n >> k;
for (int i = (0); i < (n); i++) {
cin >> t >> a >> b;
ve[a][b].push_back(t);
}
sort((ve[0][1]).begin(), (ve[0][1]).end());
sort((ve[1][0]).begin(), (ve[1][0]).end());
vector<long long> sums;
for (long long x : ve[1][1]) sums.push_back(x);
for (int i = 0; i < min(((int)(ve[0][1]).size()), ((int)(ve[1][0]).size()));
i++) {
sums.push_back(ve[0][1][i] + ve[1][0][i]);
}
sort((sums).begin(), (sums).end());
if (((int)(sums).size()) < k) {
cout << "-1\n";
return 0;
}
cout << accumulate(sums.begin(), sums.begin() + k, 0LL) << '\n';
}
| 11 | CPP |
import sys
input=sys.stdin.readline
f=lambda :list(map(int, input().strip('\n').split()))
n, k=f()
_11=[]
_01=[]
_10=[]
for _ in range(n):
t, a, b=f()
if a and b:
_11.append(t)
elif a:
_10.append(t)
elif b:
_01.append(t)
_01.sort(); _10.sort(); _11.sort()
for i in range(1, len(_01)):
_01[i]+=_01[i-1]
for i in range(1, len(_10)):
_10[i]+=_10[i-1]
for i in range(1, len(_11)):
_11[i]+=_11[i-1]
ans=3*1e9
if len(_01)>=k and len(_10)>=k:
ans=min(ans, _01[k-1]+_10[k-1])
for i in range(len(_11)):
if i+1<k and (len(_01)>=k-i-1) and (len(_10)>=k-i-1):
ans=min(ans, _11[i]+_01[k-i-2]+_10[k-i-2])
else:
if len(_11)>=k:
ans=min(ans, _11[k-1])
break
print(-1 if ans==3*1e9 else ans) | 11 | PYTHON3 |
#include <bits/stdc++.h>
using namespace std;
const int INF = 1e9;
const long long INFLL = 0x3f3f3f3f3f3f3f3f;
const int MOD = 1e9 + 7;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n, k;
cin >> n >> k;
vector<int> alice, bobo, osdois;
for (int i = 0; i < n; i++) {
bool a, b;
int t;
cin >> t >> a >> b;
if (a and b) {
osdois.push_back(t);
} else if (a) {
alice.push_back(t);
} else if (b) {
bobo.push_back(t);
}
}
sort(alice.begin(), alice.end());
sort(bobo.begin(), bobo.end());
sort(osdois.begin(), osdois.end());
queue<int> al, bb, ab;
for (auto num : alice) al.push(num);
for (auto num : bobo) bb.push(num);
for (auto num : osdois) ab.push(num);
int ans = 0;
int cont = 0;
while (cont < k) {
if (ab.empty()) {
if (bb.empty() or al.empty()) break;
ans += bb.front();
ans += al.front();
bb.pop();
al.pop();
cont++;
continue;
}
if (al.empty() or bb.empty()) {
ans += ab.front();
cont++;
ab.pop();
} else {
if (al.front() + bb.front() < ab.front()) {
ans += al.front() + bb.front();
al.pop();
bb.pop();
cont++;
} else {
ans += ab.front();
cont++;
ab.pop();
}
}
}
if (cont != k) {
cout << -1 << endl;
return 0;
}
cout << ans << endl;
return 0;
}
| 11 | CPP |
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, k, res = 0;
cin >> n >> k;
vector<int> arrAB;
vector<int> arrA;
vector<int> arrB;
for (int i = 0; i < n; i++) {
int time, a, b;
cin >> time >> a >> b;
if (a == 1 && b == 1) {
arrAB.push_back(time);
} else if (a == 1) {
arrA.push_back(time);
} else if (b == 1) {
arrB.push_back(time);
}
}
sort(arrA.begin(), arrA.end());
sort(arrB.begin(), arrB.end());
for (int i = 0; i < arrA.size() && i < arrB.size(); i++) {
arrAB.push_back(arrA[i] + arrB[i]);
}
sort(arrAB.begin(), arrAB.end());
if (arrAB.size() < k)
cout << "-1" << endl;
else {
for (int i = 0; i < k; i++) res += arrAB[i];
cout << res << endl;
}
return 0;
}
| 11 | CPP |
from collections import deque
n, k = map(int, input().split())
onla = []
onlb = []
both = []
for i in range(n):
a, b, c = map(int, input().split())
if b == 1 and c == 1:
both.append(a)
elif c == 1:
onlb.append(a)
elif b == 1:
onla.append(a)
if len(both) + len(onla) < k or len(both) + len(onlb) < k:
print(-1)
else:
onlb.sort()
onlb = deque(onlb)
onla.sort()
onla = deque(onla)
both.sort()
both = deque(both)
al = k
bob = k
ans = 0
while al > 0 or bob > 0:
if al > 0 and bob > 0:
if len(onla) == 0 or len(onlb) == 0:
ans += both[0]
al -= 1
bob -= 1
both.popleft()
else:
if len(both) == 0:
ans += onla[0] + onlb[0]
al -= 1
bob -= 1
onla.popleft()
onlb.popleft()
else:
if onla[0] + onlb[0] <= both[0]:
ans += onla[0] + onlb[0]
al -= 1
bob -= 1
onla.popleft()
onlb.popleft()
else:
ans += both[0]
al -= 1
bob -= 1
both.popleft()
elif bob > 0:
if both[0] < onlb[0]:
ans += both[0]
bob -= 1
both.popleft()
else:
ans += onlb[0]
bob -= 1
onlb.popleft()
elif al > 0:
if both[0] < onla[0]:
ans += both[0]
bob -= 1
both.popleft()
else:
ans += onla[0]
bob -= 1
onlb.popleft()
print(ans) | 11 | PYTHON3 |
class Book:
def __init__(self, time, for_alice, for_bob):
self.time = time
self.for_alice = bool(for_alice)
self.for_bob = bool(for_bob)
self.status = ('A' if self.for_alice else '') + ('B' if self.for_bob else '')
def get(li, i):
try:
return li[i].time
except IndexError:
return 10 ** 10
n, k = map(int, input().split())
books = [Book(*map(int, input().split())) for _ in range(n)]
alice_rest, bob_rest = k, k
for_alice_books = list(filter(lambda x: x.status == 'A', books))
for_bob_books = list(filter(lambda x: x.status == 'B', books))
for_both_books = list(filter(lambda x: x.status == 'AB', books))
for_alice_books = sorted(for_alice_books, key=lambda x: x.time)
for_bob_books = sorted(for_bob_books, key=lambda x: x.time)
for_both_books = sorted(for_both_books, key=lambda x: x.time)
for_alice_books_index, for_bob_books_index, for_both_books_index = 0, 0, 0
total = 0
while alice_rest > 0 or bob_rest > 0:
alice_var = get(for_alice_books, for_alice_books_index)
bob_var = get(for_bob_books, for_bob_books_index)
both_var = get(for_both_books, for_both_books_index)
if all(i == 10 ** 10 for i in [alice_var, bob_var, both_var]):
total = -1
break
if alice_rest > 0 and bob_rest > 0:
if alice_var + bob_var > both_var:
for_both_books_index += 1
total += both_var
else:
for_alice_books_index += 1
for_bob_books_index += 1
total += alice_var + bob_var
alice_rest -= 1
bob_rest -= 1
elif alice_rest == 0:
if bob_var > both_var:
for_both_books_index += 1
total += both_var
else:
for_bob_books_index += 1
total += bob_var
bob_rest -= 1
else:
if alice_var > both_var:
for_both_books_index += 1
total += both_var
else:
for_alice_books_index += 1
total += alice_var
alice_rest -= 1
print(total if total < 10 ** 10 else -1)
| 11 | PYTHON3 |
from sys import stdin
input=stdin.readline
def answer():
if(n3+n1 < k or n3+n2 < k):return -1
i,j=0,0
ans=0
for take in range(k):
if(i >= n1 or i >= n2):
ans+=common[j]
j+=1
elif(j >= n3):
ans+=a[i]+b[i]
i+=1
else:
if(a[i]+b[i] > common[j]):
ans+=common[j]
j+=1
else:
ans+=a[i]+b[i]
i+=1
return ans
n,k=map(int,input().split())
a,b,common=[],[],[]
for i in range(n):
t,x,y=map(int,input().split())
if(x and y):common.append(t)
elif(x==1 and y==0):a.append(t)
elif(x==0 and y==1):b.append(t)
common.sort()
a.sort()
b.sort()
n1,n2,n3=len(a),len(b),len(common)
print(answer())
| 11 | PYTHON3 |
nb_books, mins = [int(x) for x in input().split()]
x, y, z = [],[],[]
for i in range(nb_books):
n, a, b = [int(x) for x in input().split()]
if a & b:z.append(n)
elif a:x.append(n)
elif b:y.append(n)
x.sort()
y.sort()
for i in range(min(len(x), len(y))) :
z.append(x[i] + y[i])
answer = sum(sorted(z)[:mins])
print(-1 if len(z) < mins else answer)
| 11 | PYTHON3 |
n, k = map(int, input().split())
books = []
alice = []
bob = []
for _ in range(n):
book = tuple(map(int, input().split()))
if book[1] == book[2] == 1:
books.append(book[0])
elif book[1] == 1:
alice.append(book[0])
elif book[2] == 1:
bob.append(book[0])
for a, b in zip(sorted(alice), sorted(bob)):
books.append(a+b)
print(sum(sorted(books)[:k]) if len(books) >= k else -1)
| 11 | PYTHON3 |
#include <bits/stdc++.h>
#pragma GCC optimize("O3")
#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
using namespace std;
const long long maxn = 15e5 + 10;
const long long inf = 1e14;
long long n, m, k, t;
long long cur1, cur2;
long long C[maxn];
vector<long long> ANS;
vector<pair<long long, long long> > X[4];
void add(vector<long long> good) {
long long mn = inf + 1, mni = 3;
for (long long q = 0; q < 4; q++) {
if (!good[q]) {
continue;
}
if (X[q].back().first < mn) {
mn = X[q].back().first;
mni = q;
}
}
ANS.push_back(X[mni].back().second);
X[mni].pop_back();
if (mni / 2 == 1) {
cur2 = max(0LL, cur2 - 1);
}
if (mni % 2 == 1) {
cur1 = max(0LL, cur1 - 1);
}
}
void add1() { add({0, 1, 0, 1}); }
void add2() { add({0, 0, 1, 1}); }
void add0() { add({1, 1, 1, 1}); }
void add3() { add({0, 0, 0, 1}); }
void add_def() {
long long q, w, e;
vector<long long> mni = {0, 1};
long long mn = inf;
for (q = 0; q < 4; q++) {
for (w = q + 1; w < 4; w++) {
if ((q | w) != 3) {
continue;
}
vector<long long> dmni = {q, w};
long long dmn = X[q].back().first + X[w].back().first;
if (dmn < mn) {
mn = dmn;
mni = dmni;
}
}
}
for (auto i : mni) {
ANS.push_back(X[i].back().second);
X[i].pop_back();
if (i / 2 == 1) {
cur2 = max(cur2 - 1, 0LL);
}
if (i % 2 == 1) {
cur2 = max(cur2 - 1, 0LL);
}
}
}
bool used[maxn];
long long I[maxn];
int main() {
ios_base ::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
;
long long q, w, e, a, b, c;
cin >> n >> m >> k;
cur1 = cur2 = k;
vector<pair<long long, long long> > ALL;
for (q = 0; q < n; q++) {
cin >> a >> b >> c;
C[q] = a;
long long i = b * 2 + c;
X[i].push_back(make_pair(a, q));
ALL.push_back(make_pair(a, q));
}
for (q = 0; q < n; q++) {
for (w = 0; w < 4; w++) {
X[w].push_back(make_pair(inf, n + q * 4 + w));
ALL.push_back(make_pair(inf, n + q * 4 + w));
}
}
long long alln = n + n * 4;
sort(ALL.begin(), ALL.end());
for (q = 0; q < 4; q++) {
sort(X[q].begin(), X[q].end());
}
long long mn = 1e18, mni = 0;
long long cur = 0;
for (q = 0; q < k; q++) {
cur += X[3][q].first;
used[X[3][q].second] = 1;
}
for (q = 0; q < ALL.size(); q++) {
I[ALL[q].second] = q;
}
long long cnt = 0;
for (q = 0; cnt < m - k; q++) {
if (used[ALL[q].second]) {
continue;
}
cur += ALL[q].first;
cnt++;
}
long long iall = q - 1;
if (cur < mn) {
mn = cur;
mni = k;
}
for (q = k - 1; q >= 0; q--) {
if (q + 2 * (k - q) > m) {
break;
}
used[X[3][q].second] = 0;
cur -= X[3][q].first;
if (I[X[3][q].second] <= iall) {
cur -= ALL[iall].first;
cur += X[3][q].first;
iall--;
while (iall >= 0 && used[ALL[iall].second]) {
iall--;
}
}
long long i1 = k - q - 1;
used[X[2][i1].second] = 1;
cur += X[2][i1].first;
if (I[X[2][i1].second] <= iall) {
cur -= X[2][i1].first;
iall++;
while (used[ALL[iall].second]) {
iall++;
}
cur += ALL[iall].first;
}
used[X[1][i1].second] = 1;
cur += X[1][i1].first;
if (I[X[1][i1].second] <= iall) {
cur -= X[1][i1].first;
iall++;
while (used[ALL[iall].second]) {
iall++;
}
cur += ALL[iall].first;
}
cur -= ALL[iall].first;
iall--;
while (iall >= 0 && used[ALL[iall].second]) {
iall--;
}
if (cur < mn) {
mn = cur;
mni = q;
}
}
for (q = 0; q < alln; q++) {
used[q] = 0;
}
for (q = 0; q < mni; q++) {
ANS.push_back(X[3][q].second);
used[X[3][q].second] = 1;
}
for (q = 0; q < k - mni; q++) {
ANS.push_back(X[1][q].second);
used[X[1][q].second] = 1;
ANS.push_back(X[2][q].second);
used[X[2][q].second] = 1;
}
cnt = 0;
for (q = 0; cnt < m - mni - 2 * (k - mni); q++) {
if (!used[ALL[q].second]) {
ANS.push_back(ALL[q].second);
cnt++;
}
}
for (auto i : ANS) {
if (i >= n) {
cout << -1;
return 0;
}
}
cout << mn << endl;
for (q = 0; q < ANS.size(); q++) {
cout << ANS[q] + 1 << " ";
}
return 0;
}
| 11 | CPP |
from sys import stdin,stdout
# stdin = open("input.txt","r")
# stdout = open("output.txt","w")
n,k = stdin.readline().strip().split(' ')
n,k = int(n),int(k)
books=[]
for i in range(n):
t,a,b=stdin.readline().strip().split(' ')
t,a,b=int(t),int(a),int(b)
books.append((t,a,b))
pairs_a=[]
pairs_b=[]
single=[]
for i in books:
if i[1]==1 and i[2]==1:
single.append(i[0])
elif i[1] or i[2]==1:
if i[1]==1:
pairs_a.append(i[0])
else:
pairs_b.append(i[0])
pairs_b=sorted(pairs_b)
pairs_a=sorted(pairs_a)
# print(single)
# print(pairs_a)
# print(pairs_b)
pairs=[]
for i in range(min(len(pairs_a),len(pairs_b))):
single.append(pairs_a[i]+pairs_b[i])
single=sorted(single)
if len(single)<k:
stdout.write(str(-1)+"\n")
else:
stdout.write(str(sum(single[:k]))+"\n")
| 11 | PYTHON3 |
n, k = map(int, input().split())
alice=[];bob=[];both=[]
for _ in range(n):
x,y,z=map(int,input().split())
if y==1 and z==1:
both.append(x)
elif y==1:
alice.append(x)
elif z==1:
bob.append(x)
alice.sort();bob.sort()
# print(alice)
for i in range(min(len(alice),len(bob))):
both.append(alice[i]+bob[i])
both.sort()
# print(both)
if len(both)<k:
print(-1)
else:
print(sum(both[:k])) | 11 | PYTHON3 |
#include <bits/stdc++.h>
using namespace std;
int solve() {
int n, k;
cin >> n >> k;
int a, b, ans;
ans = a = b = 0;
priority_queue<int> x, y, z;
while (n--) {
int t, u, v;
cin >> t >> u >> v;
t *= -1;
if (u && v) {
z.push(t);
} else if (u) {
x.push(t);
} else if (v) {
y.push(t);
}
}
while (!x.empty() && !y.empty() && !z.empty() && a < k) {
int u, v, w;
u = -x.top();
v = -y.top();
w = -z.top();
if (u + v < w) {
ans += u + v;
x.pop();
y.pop();
} else {
ans += w;
z.pop();
}
++a;
++b;
}
while (a < k && !z.empty() && x.empty()) {
ans += -z.top();
z.pop();
++a;
++b;
}
while (b < k && !z.empty() && y.empty()) {
ans += -z.top();
z.pop();
++a;
++b;
}
while (a < k && !x.empty() && !z.empty()) {
int u = -x.top();
int w = -z.top();
if (u < w) {
ans += u;
++a;
x.pop();
} else {
ans += w;
++a;
++b;
z.pop();
}
}
while (a < k && !x.empty()) {
ans += -x.top();
x.pop();
++a;
}
while (b < k && !y.empty() && !z.empty()) {
int u = -y.top();
int w = -z.top();
if (u < w) {
ans += u;
++b;
y.pop();
} else {
ans += w;
++a;
++b;
z.pop();
}
}
while (b < k && !y.empty()) {
ans += -y.top();
y.pop();
++b;
}
if (a < k || b < k)
cout << "-1\n";
else
cout << ans << '\n';
return 0;
}
int main() {
cin.tie(0)->sync_with_stdio(0);
int t = 1;
while (t--) solve();
return 0;
}
| 11 | CPP |
def main():
n,k=list(map(int,input().split()))
l=[]
c1=0
c2=0
for j in range(0,n):
l1=list(map(int,input().split()))
if l1[1]==1:
c1+=1
if l1[2]==1:
c2+=1
l.append(l1)
if c1<k or c2<k:
print(-1)
return
c=0
d={}
l2=[]
l3=[]
l4=[]
for j in range(0,n):
if l[j][1]==1 and l[j][2]==1:
l4.append(l[j][0])
elif l[j][1]==1:
l2.append(l[j][0])
elif l[j][2]==1:
l3.append(l[j][0])
m=10**9+7
l2.append(m)
l3.append(m)
l4.append(m)
l2.sort()
l3.sort()
l4.sort()
#print(l2,l3,l4)
p1=0
p2=0
p3=0
f=0
k1=k
k2=k
j=0
while k1!=0 or k2!=0:
if l2[p1]+l3[p2] >= l4[p3] and p3!=len(l4)-1:
c+=l4[p3]
if p3!=len(l4)-1:
p3+=1
k1-=1
k2-=1
else:
if k1!=0 and p1!=len(l2)-1:
c+=l2[p1]
if p1!=len(l2)-1:
p1+=1
k1-=1
if k2!=0 and p2!=len(l3)-1:
c+=l3[p2]
if p2!=len(l3)-1:
p2+=1
k2-=1
if k1==0 and k2==0:
break
print(c)
t=1
for i in range(0,t):
main()
| 11 | PYTHON3 |
import sys
from functools import lru_cache, cmp_to_key
from heapq import merge, heapify, heappop, heappush, nsmallest
from math import ceil, floor, gcd, fabs, factorial, fmod, sqrt, inf
from collections import defaultdict as dd, deque, Counter as C
from itertools import combinations as comb, permutations as perm
from bisect import bisect_left as bl, bisect_right as br, bisect
from time import perf_counter
from fractions import Fraction
# sys.setrecursionlimit(pow(10, 6))
# sys.stdin = open("input.txt", "r")
# sys.stdout = open("output.txt", "w")
mod = pow(10, 9) + 7
mod2 = 998244353
def data(): return sys.stdin.readline().strip()
def out(*var, end="\n"): sys.stdout.write(' '.join(map(str, var))+end)
def l(): return list(sp())
def sl(): return list(ssp())
def sp(): return map(int, data().split())
def ssp(): return map(str, data().split())
def l1d(n, val=0): return [val for i in range(n)]
def l2d(n, m, val=0): return [l1d(n, val) for j in range(m)]
"""
pppppppppppppppppppp
ppppp ppppppppppppppppppp
ppppppp ppppppppppppppppppppp
pppppppp pppppppppppppppppppppp
pppppppppppppppppppppppppppppppp
pppppppppppppppppppppppp
ppppppppppppppppppppppppppppppppppppppppppppppp pppppppppppppppppppp
pppppppppppppppppppppppppppppppppppppppppppppppp ppppppppppppppppppppp
ppppppppppppppppppppppppppppppppppppppppppppppppp pppppppppppppppppppppp
ppppppppppppppppppppppppppppppppppppppppppppppp pppppppppppppppppppppppp
pppppppppppppppppppppppppppppppppppppppppppppp pppppppppppppppppppppppppp
ppppppppppppppppppppppppppppppppppppppppppppp pppppppppppppppppppppppppppp
pppppppppppppppppppppppppppppppp pppppppppppppppppppppppppppppppp
pppppppppppppppppppppppppppp pppppppppppppppppppppppppppppppppppppppppppppp
ppppppppppppppppppppppppppp pppppppppppppppppppppppppppppppppppppppppppppppp
pppppppppppppppppppppppp pppppppppppppppppppppppppppppppppppppppppppppppppp
ppppppppppppppppppppppp ppppppppppppppppppppppppppppppppppppppppppppppppp
pppppppppppppppppppppp ppppppppppppppppppppppppppppppppppppppppppppppp
ppppppppppppppppppppp ppppppppppppppppppppppppppppppppppppppppppppp
pppppppppppppppppppppppp
pppppppppppppppppppppppppppppppp
pppppppppppppppppppppp pppppppp
ppppppppppppppppppppp ppppppp
ppppppppppppppppppp ppppp
pppppppppppppppppppp
"""
n, k = sp()
mat = []
a, b, both = [], [], []
for i in range(n):
ti, ai, bi = sp()
if ai and bi:
both.append(ti)
continue
if ai:
a.append(ti)
if bi:
b.append(ti)
if len(a) + len(both) < k or len(b) + len(both) < k:
out(-1)
exit()
a.sort(reverse=True)
b.sort(reverse=True)
both.sort(reverse=True)
answer = 0
for i in range(k):
t1 = inf if not a else a[-1]
t2 = inf if not b else b[-1]
t3 = inf if not both else both[-1]
if t3 < t1 + t2:
answer += t3
both.pop()
else:
answer += t1 + t2
a.pop()
b.pop()
out(answer)
| 11 | PYTHON3 |
#include <bits/stdc++.h>
using namespace std;
inline long long read() {
long long r = 0, f = 0;
char c;
while (!isdigit(c = getchar())) f |= (c == '-');
while (isdigit(c)) r = (r << 1) + (r << 3) + (c ^ 48), c = getchar();
return f ? -r : r;
}
inline long long min(long long a, long long b) { return a < b ? a : b; }
struct Book {
long long t, a, b;
bool operator<(const Book &book) const {
return t ^ book.t ? t < book.t : (a & b) > (book.a & book.b);
}
} b[202202];
long long n, k, sum, ans, cnt[2], size[2], s[2][202202];
inline void work() {
n = read(), k = read();
for (long long i = 1; i <= n; i++) {
b[i].t = read();
b[i].a = read();
b[i].b = read();
if (b[i].a | b[i].b) sum += b[i].t;
cnt[0] += b[i].a;
cnt[1] += b[i].b;
}
if (cnt[0] < k || cnt[1] < k) {
puts("-1");
return;
}
sort(b + 1, b + 1 + n);
for (long long i = n; i >= 1; i--)
if (b[i].a && !b[i].b) {
s[0][size[0] + 1] = s[0][size[0]];
size[0]++;
s[0][size[0]] += b[i].t;
}
for (long long i = size[0] + 1; i <= n; i++) s[0][i] = s[0][size[0]];
for (long long i = n; i >= 1; i--)
if (b[i].b && !b[i].a) {
s[1][size[1] + 1] = s[1][size[1]];
size[1]++;
s[1][size[1]] += b[i].t;
}
for (long long i = size[1] + 1; i <= n; i++) s[1][i] = s[1][size[1]];
ans = sum - s[0][cnt[0] - k] - s[1][cnt[1] - k];
for (long long i = n; i >= 1; i--) {
if (cnt[0] == k || cnt[1] == k) break;
if (!(b[i].a & b[i].b)) continue;
cnt[0]--, cnt[1]--;
sum -= b[i].t;
ans = min(ans, sum - s[0][cnt[0] - k] - s[1][cnt[1] - k]);
}
printf("%lld", ans);
}
signed main() {
work();
return 0;
}
| 11 | CPP |
n, k = list(map(int, input().split()))
a = []
b = []
ab = []
for _ in range(0, n):
t, x, y = list(map(int, input().split()))
if (x == 1 and y == 1):
ab.append(t)
elif (x == 1):
a.append(t)
elif (y == 1):
b.append(t)
# print(a, b, ab)
ab.sort(reverse=True)
b.sort(reverse=True)
a.sort(reverse=True)
ca = 0
cb = 0
t = 0
c = 0
u = 0
while (len(a) != 0 and len(b) != 0):
if (len(ab) > 0 and ab[-1] <= a[-1] + b[-1]):
t += ab.pop()
c += 1
else:
t = t + a.pop() + b.pop()
c += 1
if (c == k):
u = 1
break
if (u == 1):
print(t)
elif (c + len(ab) < k):
print(-1)
else:
t += sum(ab[-(k - c):])
print(t)
| 11 | PYTHON3 |
import sys
input = sys.stdin.readline
n, k = map(int, input().split())
o, a, b = [], [], []
for i in range(n):
q, w, e = map(int, input().split())
if w == e and w:
o.append(q)
elif w and not e:
a.append(q)
elif w or e:
b.append(q)
i = j = l = 0
done = 0
ans = 0
o.sort()
a.sort()
b.sort()
while (i < len(o) or j < len(a) and l < len(b)) and done < k:
if i < len(o) and (j >= len(a) or l >= len(b) or j < len(a) and l < len(b) and o[i] <= a[j]+b[l]):
ans += o[i]
i += 1
done += 1
elif l < len(b) and j < len(a):
ans += a[j]+b[l]
j += 1
l += 1
done += 1
print(ans if done >= k else -1) | 11 | PYTHON3 |
n,k = list(map(int,input().split()))
ca,cb=0,0
x,y,z = [],[],[]
for i in range(n):
t,a,b, = list(map(int,input().split()))
ca+=a
cb+=b
if(a==1 and b==0):
x.append(t)
elif(a==0 and b==1):
y.append(t)
elif(a==1 and b==1):
z.append(t)
x.sort()
y.sort()
z.sort()
if(ca<k or cb<k):
print("-1")
else:
total = 0
arr = []
for i in range(min(len(z),k)):
total += z[i]
arr.append(z[i])
if(len(z)<k):
for i in range(len(z),k):
total+= x[0]+y[0]
del x[0]
del y[0]
while(len(x)>0 and len(y)>0 and len(arr)>0 and x[0]+y[0]<arr[-1]):
total += (x[0]+y[0]-arr[-1])
del arr[-1]
del x[0]
del y[0]
print(total) | 11 | PYTHON3 |
#include <bits/stdc++.h>
using namespace std;
const long long INF = 1e18;
namespace BF {
long long solve(int N, int M, int K, const vector<int>& T, const vector<int>& A,
const vector<int>& B) {
long long res = INF;
for (int mask = 0, _n = (1 << N); mask < _n; ++mask) {
if ((__builtin_popcount((mask))) != M) continue;
int cntA = 0, cntB = 0;
long long cur = 0;
for (int i = 0, _n = (N); i < _n; ++i) {
if (mask & (1 << i)) {
if (A[i]) cntA++;
if (B[i]) cntB++;
cur += T[i];
}
}
if (cntA >= K && cntB >= K) res = min(res, cur);
}
return res < INF ? res : -1;
}
} // namespace BF
struct Item {
int id, value;
bool operator<(const Item i) const {
if (value != i.value) return value < i.value;
return id < i.id;
}
bool operator>(const Item i) const {
if (value != i.value) return value > i.value;
return id > i.id;
}
};
ostream& operator<<(ostream& out, Item const& item) {
return out << "(" << item.id << ':' << item.value << ")";
}
class MBest {
long long best_sum;
multiset<int, greater<int> > le;
multiset<int> gt;
void transfer_gt_to_le() {
assert(!gt.empty());
auto it = gt.begin();
le.insert(*it);
best_sum += *it;
gt.erase(it);
}
void transfer_le_to_gt() {
assert(!le.empty());
auto it = le.begin();
gt.insert(*it);
best_sum -= *it;
le.erase(it);
}
public:
MBest() : best_sum(0) {}
int getM() const { return le.size(); }
long long query_best_sum() const { return best_sum; }
void add(int x) {
le.insert(x);
best_sum += x;
transfer_le_to_gt();
}
void remove(int x) {
auto it_gt = gt.find(x);
if (it_gt != gt.end()) {
gt.erase(it_gt);
return;
}
auto it_le = le.find(x);
assert(it_le != le.end());
le.erase(it_le);
best_sum -= x;
transfer_gt_to_le();
}
void increaseM() { transfer_gt_to_le(); }
};
vector<long long> get_psum(const vector<Item>& V) {
vector<long long> res(int((V).size()));
for (int i = (1), _b = (int((V).size()) - 1); i <= _b; ++i)
res[i] = res[i - 1] + V[i].value;
return res;
}
long long solve(int N, int M, int K, const vector<int>& T, const vector<int>& A,
const vector<int>& B) {
MBest mb;
vector<Item> alice, bob, both;
for (int i = 0, _n = (N); i < _n; ++i) {
Item item = {i + 1, T[i]};
if (A[i] && B[i])
both.push_back(item);
else if (A[i])
alice.push_back(item);
else if (B[i])
bob.push_back(item);
else
mb.add(item.value);
}
int minj = min(int((alice).size()), int((bob).size()));
if (minj + int((both).size()) < K) {
cout << "-1" << '\n';
return -1;
}
sort(alice.begin(), alice.end());
sort(bob.begin(), bob.end());
sort(both.begin(), both.end());
minj = min(minj, K);
for (int j = (minj), _b = (int((alice).size()) - 1); j <= _b; ++j)
mb.add(alice[j].value);
alice.erase(alice.begin() + minj, alice.end());
alice.insert(alice.begin(), {0, 0});
for (int j = (minj), _b = (int((bob).size()) - 1); j <= _b; ++j)
mb.add(bob[j].value);
bob.erase(bob.begin() + minj, bob.end());
bob.insert(bob.begin(), {0, 0});
both.insert(both.begin(), {0, 0});
for (int k = (K - minj), _b = (int((both).size()) - 1); k <= _b; ++k)
mb.add(both[k].value);
vector<long long> psum_alice = get_psum(alice);
vector<long long> psum_bob = get_psum(bob);
vector<long long> psum_both = get_psum(both);
long long res = INF;
int bestj = -1;
for (int j = minj; j >= 0; --j) {
int k = K - j;
if (k >= int((both).size())) break;
mb.remove(both[k].value);
int nbooks = K + j;
if (nbooks <= M) {
int nmissing = M - nbooks;
while (mb.getM() < nmissing) mb.increaseM();
long long best_other = mb.query_best_sum();
long long cur = psum_alice[j] + psum_bob[j] + psum_both[k] + best_other;
if (res > cur) {
bestj = j;
res = cur;
}
}
if (j > 0) {
mb.add(alice[j].value);
mb.add(bob[j].value);
}
}
if (bestj < 0) {
cout << "-1\n";
return -1;
}
set<Item> avail;
for (int i = 0, _n = (N); i < _n; ++i) avail.insert({i + 1, T[i]});
vector<int> best_books;
for (int j = (1), _b = (bestj); j <= _b; ++j) {
Item item = alice[j];
avail.erase(item);
best_books.push_back(item.id);
}
for (int j = (1), _b = (bestj); j <= _b; ++j) {
Item item = bob[j];
avail.erase(item);
best_books.push_back(item.id);
}
for (int k = (1), _b = (K - bestj); k <= _b; ++k) {
Item item = both[k];
avail.erase(item);
best_books.push_back(item.id);
}
assert(int((best_books).size()) <= M);
while (int((best_books).size()) < M) {
auto it = avail.begin();
best_books.push_back(it->id);
avail.erase(it);
}
cout << res << '\n';
long long sum = 0;
for (int id : best_books) {
cout << id << ' ';
sum += T[id - 1];
}
cout << '\n';
return res;
}
int main(int argc, char* argv[]) {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int N, M, K;
cin >> N >> M >> K;
vector<int> T(N), A(N), B(N);
for (int i = 0, _n = (N); i < _n; ++i) cin >> T[i] >> A[i] >> B[i];
solve(N, M, K, T, A, B);
return 0;
}
| 11 | CPP |
#include <bits/stdc++.h>
using namespace std;
class Solve {
public:
void updateSt(set<pair<int, int>> &st, set<pair<int, int>> &fr, int &sum,
int need) {
need = max(need, 0);
while (true) {
bool useful = false;
while (st.size() > need) {
sum -= st.rbegin()->first;
fr.insert(*st.rbegin());
st.erase(prev(st.end()));
useful = true;
}
while (st.size() < need && fr.size() > 0) {
sum += fr.begin()->first;
st.insert(*fr.begin());
fr.erase(fr.begin());
useful = true;
}
while (!st.empty() && !fr.empty() &&
fr.begin()->first < st.rbegin()->first) {
sum -= st.rbegin()->first;
sum += fr.begin()->first;
fr.insert(*st.rbegin());
st.erase(prev(st.end()));
st.insert(*fr.begin());
fr.erase(fr.begin());
useful = true;
}
if (!useful) break;
}
}
void main() {
const int INF = 10e9;
int n, m, k;
cin >> n >> m >> k;
vector<pair<int, int>> times[4];
vector<int> sums[4];
for (int i = 0; i < n; ++i) {
int t, a, b;
cin >> t >> a >> b;
times[a * 2 + b].push_back({t, i});
}
for (int i = 0; i < 4; ++i) {
sort(times[i].begin(), times[i].end());
sums[i].push_back(0);
for (auto it : times[i]) {
sums[i].push_back(sums[i].back() + it.first);
}
}
int ans = INF;
int pos = INF;
set<pair<int, int>> st;
set<pair<int, int>> fr;
int sum = 0;
vector<int> res;
for (int iter = 0; iter < 2; ++iter) {
st.clear();
fr.clear();
sum = 0;
int start = 0;
while (k - start >= sums[1].size() || k - start >= sums[2].size() ||
m - start - (k - start) * 2 < 0) {
++start;
}
if (start >= sums[3].size()) {
cout << -1 << endl;
return;
}
int need = m - start - (k - start) * 2;
for (int i = 0; i < 3; ++i) {
for (int p = times[i].size() - 1; p >= (i == 0 ? 0 : k - start); --p) {
fr.insert(times[i][p]);
}
}
updateSt(st, fr, sum, need);
for (int cnt = start; cnt < (iter == 0 ? sums[3].size() : pos); ++cnt) {
if (k - cnt >= 0) {
if (cnt + (k - cnt) * 2 + st.size() == m) {
if (ans >
sums[3][cnt] + sums[1][k - cnt] + sums[2][k - cnt] + sum) {
ans = sums[3][cnt] + sums[1][k - cnt] + sums[2][k - cnt] + sum;
pos = cnt + 1;
}
}
} else {
if (cnt + st.size() == m) {
if (ans > sums[3][cnt] + sum) {
ans = sums[3][cnt] + sum;
pos = cnt + 1;
}
}
}
if (iter == 1 && cnt + 1 == pos) break;
need -= 1;
if (k - cnt > 0) {
need += 2;
fr.insert(times[1][k - cnt - 1]);
fr.insert(times[2][k - cnt - 1]);
}
updateSt(st, fr, sum, need);
}
if (iter == 1) {
for (int i = 0; i + 1 < pos; ++i) res.push_back(times[3][i].second);
for (int i = 0; i <= k - pos; ++i) {
res.push_back(times[1][i].second);
res.push_back(times[2][i].second);
}
for (auto [value, position] : st) res.push_back(position);
}
}
cout << ans << endl;
for (auto it : res) cout << it + 1 << " ";
cout << endl;
return;
}
};
int main(int argc, const char *argv[]) {
Solve s;
s.main();
return 0;
}
| 11 | CPP |
## necessary imports
import sys
input = sys.stdin.readline
#from math import ceil, floor, factorial;
# swap_array function
def swaparr(arr, a,b):
temp = arr[a];
arr[a] = arr[b];
arr[b] = temp
## gcd function
def gcd(a,b):
if b == 0:
return a
return gcd(b, a % b);
## nCr function efficient using Binomial Cofficient
def nCr(n, k):
if(k > n - k):
k = n - k
res = 1
for i in range(k):
res = res * (n - i)
res = res / (i + 1)
return int(res)
## upper bound function code -- such that e in a[:i] e < x;
def upper_bound(a, x, lo=0):
hi = len(a)
while lo < hi:
mid = (lo+hi)//2
if a[mid] < x:
lo = mid+1
else:
hi = mid
return lo
## prime factorization
def primefs(n):
## if n == 1 ## calculating primes
primes = {}
while(n%2 == 0 and n > 0):
primes[2] = primes.get(2, 0) + 1
n = n//2
for i in range(3, int(n**0.5)+2, 2):
while(n%i == 0 and n > 0):
primes[i] = primes.get(i, 0) + 1
n = n//i
if n > 2:
primes[n] = primes.get(n, 0) + 1
## prime factoriazation of n is stored in dictionary
## primes and can be accesed. O(sqrt n)
return primes
## MODULAR EXPONENTIATION FUNCTION
def power(x, y, p):
res = 1
x = x % p
if (x == 0) :
return 0
while (y > 0) :
if ((y & 1) == 1) :
res = (res * x) % p
y = y >> 1
x = (x * x) % p
return res
## DISJOINT SET UNINON FUNCTIONS
def swap(a,b):
temp = a
a = b
b = temp
return a,b
# find function with path compression included (recursive)
# def find(x, link):
# if link[x] == x:
# return x
# link[x] = find(link[x], link);
# return link[x];
# find function with path compression (ITERATIVE)
def find(x, link):
p = x;
while( p != link[p]):
p = link[p];
while( x != p):
nex = link[x];
link[x] = p;
x = nex;
return p;
# the union function which makes union(x,y)
# of two nodes x and y
def union(x, y, link, size):
x = find(x, link)
y = find(y, link)
if size[x] < size[y]:
x,y = swap(x,y)
if x != y:
size[x] += size[y]
link[y] = x
## returns an array of boolean if primes or not USING SIEVE OF ERATOSTHANES
def sieve(n):
prime = [True for i in range(n+1)]
p = 2
while (p * p <= n):
if (prime[p] == True):
for i in range(p * p, n+1, p):
prime[i] = False
p += 1
return prime
#### PRIME FACTORIZATION IN O(log n) using Sieve ####
MAXN = int(1e6 + 5)
def spf_sieve():
spf[1] = 1;
for i in range(2, MAXN):
spf[i] = i;
for i in range(4, MAXN, 2):
spf[i] = 2;
for i in range(3, ceil(MAXN ** 0.5), 2):
if spf[i] == i:
for j in range(i*i, MAXN, i):
if spf[j] == j:
spf[j] = i;
## function for storing smallest prime factors (spf) in the array
################## un-comment below 2 lines when using factorization #################
# spf = [0 for i in range(MAXN)]
# spf_sieve()
def factoriazation(x):
ret = {};
while x != 1:
ret[spf[x]] = ret.get(spf[x], 0) + 1;
x = x//spf[x]
return ret
## this function is useful for multiple queries only, o/w use
## primefs function above. complexity O(log n)
## taking integer array input
def int_array():
return list(map(int, input().strip().split()))
## taking string array input
def str_array():
return input().strip().split();
#defining a couple constants
MOD = int(1e9)+7;
CMOD = 998244353;
INF = float('inf'); NINF = -float('inf');
################### ---------------- TEMPLATE ENDS HERE ---------------- ###################
n, k = int_array(); a = [];
sum_a = sum_b = 0;
for __ in range(n):
t, aa, bb = int_array();
sum_a += aa; sum_b += bb;
a.append((t, aa, bb));
if sum_a < k or sum_b < k:
print(-1);
else:
only_a = []; only_b = []; both = [];
for i in a:
if i[1] == 1 and i[2] == 0:
only_a.append(i[0]);
elif i[1] == 0 and i[2] == 1:
only_b.append(i[0]);
elif i[1] == 1 and i[2] == 1:
both.append(i[0]);
only_a.sort(); only_b.sort();
for i in range(min(len(only_a), len(only_b))):
both.append(only_a[i] + only_b[i]);
both.sort();
print(sum(both[:k])); | 11 | PYTHON3 |
######################################################
############Created by Devesh Kumar###################
#############[email protected]####################
##########For CodeForces(Devesh1102)#################
#####################2020#############################
######################################################
import sys
input = sys.stdin.readline
# import sys
import heapq
import copy
import math
import decimal
# import sys.stdout.flush as flush
# from decimal import *
#heapq.heapify(li)
#
#heapq.heappush(li,4)
#
#heapq.heappop(li)
#
# & Bitwise AND Operator 10 & 7 = 2
# | Bitwise OR Operator 10 | 7 = 15
# ^ Bitwise XOR Operator 10 ^ 7 = 13
# << Bitwise Left Shift operator 10<<2 = 40
# >> Bitwise Right Shift Operator
# '''############ ---- Input Functions ---- #######Start#####'''
def inp():
return(int(input()))
def inlt():
return(list(map(int,input().split())))
def insr():
s = input()
return(list(s[:len(s) - 1]))
def insr2():
s = input()
return((s[:len(s) - 1]))
def invr():
return(map(int,input().split()))
############ ---- Input Functions ---- #######End
# #####
def pr_list(a):
print(*a, sep=" ")
def main():
# tests = inp()
tests = 1
# mod = 1000000007
limit = 10**18
ans = 0
for test in range(tests):
[n,k] = inlt()
b = []
a = []
both = []
for i in range(n):
[t,alice,bob] = inlt()
if alice == 1 and bob == 1:
both.append(t)
elif alice == 1:
a.append(t)
elif bob == 1:
b.append(t)
both.sort()
a.sort()
b.sort()
if len(both) + len(a) <k or len(both) + len(b) <k:
print(-1)
break
# print(both,a,b)
ans = 0
a_i = 0
b_i = 0
both_i = 0
for _ in range(k):
if both_i != len(both) and a_i !=len(a) and b_i!= len(b):
if both[both_i] < a[a_i] + b[b_i]:
ans = ans + both[both_i]
both_i +=1
else:
ans = ans + a[a_i] + b[b_i]
a_i = a_i +1
b_i = b_i +1
elif both_i == len(both):
ans = ans + a[a_i] + b[b_i]
a_i = a_i +1
b_i = b_i +1
else:
ans = ans + both[both_i]
both_i +=1
print(ans)
if __name__== "__main__":
main() | 11 | PYTHON3 |
n, k = map(int, input().split())
A, B, both = [0], [0], [0]
for i in range(n):
t, a, b = map(int, input().split())
if a == 1 and b == 1:
both.append(t)
if a == 1 and b == 0:
A.append(t)
if a == 0 and b == 1:
B.append(t)
A.sort()
B.sort()
both.sort()
if len(A)-1 + len(both)-1 < k or len(B)-1 + len(both)-1 < k:
print(-1)
exit(0)
for i in range(1, len(A)):
A[i] += A[i-1]
for i in range(1, len(B)):
B[i] += B[i-1]
cur = 0
ans = 10**12 + 10
for ch in range(len(both)):
cur += both[ch]
if ch > k:
break
# Need k - ch each from A and B
if k - ch < len(A) and k - ch < len(B):
ans = min(ans, A[k-ch] + B[k-ch] + cur)
print(ans) | 11 | PYTHON3 |
line = input().split()
n,k = int(line[0]), int(line[1])
a,b,c = [],[],[]
for i in range(n):
line = input().split()
t,ai,bi = int(line[0]), int(line[1]), int(line[2])
if (ai == 1 and bi == 1):
c.append(t)
elif (ai == 1):
a.append(t)
elif (bi == 1):
b.append(t)
a.sort()
b.sort()
c.sort()
i,j,cnt = 0,0,0
ans = 0
while (i < min(len(a),len(b)) and j < len(c) and cnt < k):
if (a[i]+b[i] < c[j]):
ans += a[i]+b[i]
i += 1
else:
ans += c[j]
j += 1
cnt += 1
while (i < min(len(a),len(b)) and cnt < k):
ans += a[i]+b[i]
cnt += 1
i += 1
while (j < len(c) and cnt < k):
ans += c[j]
cnt += 1
j += 1
if (cnt < k):
print(-1)
else:
print(ans)
| 11 | PYTHON3 |
n,k=map(int,input().split(" "))
db=[]
a=[]
b=[]
for i in range(n):
t,A,B= map(int, input().split(" "))
if A==B==1:
db.append(t)
elif A==1:
a.append(t)
elif B==1:
b.append(t)
a.sort()
b.sort()
for i in range(min(len(a),len(b))):
db.append((a[i]+b[i]))
if len(db)<k:
print(-1)
else:
db.sort()
print(sum(db[:k]))
| 11 | PYTHON3 |
import os, sys
from io import IOBase, BytesIO
py2 = round(0.5)
if py2:
from future_builtins import ascii, filter, hex, map, oct, zip
range = xrange
BUFSIZE = 8192
class FastIO(BytesIO):
newlines = 0
def __init__(self, file):
self._file = file
self._fd = file.fileno()
self.writable = 'x' in file.mode or 'w' in file.mode
self.write = super(FastIO, self).write if self.writable else None
def _fill(self):
s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.seek((self.tell(), self.seek(0,2), super(FastIO, self).write(s))[0])
return s
def read(self):
while self._fill(): pass
return super(FastIO,self).read()
def readline(self):
while self.newlines == 0:
s = self._fill(); self.newlines = s.count(b'\n') + (not s)
self.newlines -= 1
return super(FastIO, self).readline()
def flush(self):
if self.writable:
os.write(self._fd, self.getvalue())
self.truncate(0), self.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
if py2:
self.write = self.buffer.write
self.read = self.buffer.read
self.readline = self.buffer.readline
else:
self.write = lambda s:self.buffer.write(s.encode('ascii'))
self.read = lambda:self.buffer.read().decode('ascii')
self.readline = lambda:self.buffer.readline().decode('ascii')
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip('\r\n')
# Cout implemented in Python
import sys
class ostream:
def __lshift__(self,a):
sys.stdout.write(str(a))
return self
cout = ostream()
endl = '\n'
def get_input(a=str):
return a(input())
def get_int_input():
return get_input(int)
def get_input_arr(a):
return list(map(a, input().split()))
def get_int_input_arr():
return get_input_arr(int)
def solve():
n, k = get_int_input_arr()
books_both = []
books_a = []
books_b = []
for _ in range(n):
t_i, a_i, b_i = get_int_input_arr()
if a_i == 1 and b_i == 1:
books_both.append(t_i)
elif a_i == 1 and b_i == 0:
books_a.append(t_i)
elif a_i == 0 and b_i == 1:
books_b.append(t_i)
books_both.sort()
books_a.sort()
books_b.sort()
prefx_both = [0] * (len(books_both) + 1)
for i in range(1, len(books_both) + 1):
prefx_both[i] = prefx_both[i - 1] + books_both[i - 1]
prefx_a = [0] * (len(books_a) + 1)
for i in range(1, len(books_a) + 1):
prefx_a[i] = prefx_a[i - 1] + books_a[i - 1]
prefx_b = [0] * (len(books_b) + 1)
for i in range(1, len(books_b) + 1):
prefx_b[i] = prefx_b[i - 1] + books_b[i - 1]
# print(books_both)
def can_do(time):
for i in range(min(k + 1, len(books_both) + 1)):
# print(i)
both_books_time = prefx_both[i]
left_nums = k - i
if left_nums < 0 or left_nums >= len(prefx_a) or left_nums >= len(prefx_b):
continue
books_a_time = prefx_a[left_nums]
books_b_time = prefx_b[left_nums]
if time >= both_books_time + books_a_time + books_b_time:
return True
return False
lo = 0
hi = 10 ** 10
res = float("inf")
while lo <= hi:
mid = lo + (hi - lo) // 2
if can_do(mid):
res = mid
hi = mid - 1
else:
lo = mid + 1
if res == float("inf"):
cout<<-1<<endl
else:
cout<<res<<endl
def main():
solve()
if __name__ == "__main__":
main() | 11 | PYTHON3 |
n,k=map(int,input().split())
a =[]
b =[]
c = []
for i in range(n):
m = [*map(int,input().split())]
if(m[1]==1 and m[2]==1):
c.append(m[0])
elif(m[1]==1):
a.append(m)
elif(m[2]==1):
b.append(m)
a.sort(key=lambda x:(x[0]))
b.sort(key=lambda x:(x[0]))
for i in range(min(len(a),len(b))):
c.append(a[i][0]+b[i][0])
c.sort()
if(len(c)<k):
print(-1)
else:
print(sum(c[i] for i in range(k)))
| 11 | PYTHON3 |
import sys
input=sys.stdin.readline
def main():
n,k=map(int,input().split())
A,B,C=[],[],[]
for i in range(n):
n,a,b=map(int,input().split())
if(a==1 and b==1):
A.append(n)
elif(a==1 and b==0):
B.append(n)
elif(a==0 and b==1):
C.append(n)
B.sort()
C.sort()
v=min(len(B),len(C))
for i in range(v):
A.append(B[i]+C[i])
if(len(A)<k):
print(-1)
else:
A.sort()
ans=0
for i in range(k):
ans=ans+A[i]
print(ans)
main()
| 11 | PYTHON3 |
#include <bits/stdc++.h>
using namespace std;
int32_t main() {
int n, m, k;
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cin >> n >> m >> k;
vector<pair<int, int> > ab;
vector<pair<int, int> > a;
vector<pair<int, int> > b;
vector<pair<int, int> > non;
for (int i = 0; i < n; i++) {
int t, a1, b1;
cin >> t >> a1 >> b1;
if (a1 && b1) {
ab.push_back({t, i});
} else if (a1) {
a.push_back({t, i});
} else if (b1) {
b.push_back({t, i});
} else {
non.push_back({t, i});
}
}
sort(ab.begin(), ab.end());
sort(a.begin(), a.end());
sort(b.begin(), b.end());
sort(non.begin(), non.end());
int l = -1;
for (int i = 0; i <= min(k, (int)ab.size()); i++) {
if (k - i <= (int)a.size() && k - i <= (int)b.size() &&
((k - i) * 2 + i <= m)) {
l = i;
break;
}
}
if (l == -1) {
cout << -1;
return 0;
}
set<pair<int, int> > curr;
set<pair<int, int> > all;
int r1 = l, r2 = k - l;
long long ans;
long long curr_sum = 0;
int ans_r1 = r1, ans_r2 = r2;
int curr_el = r2 * 2 + r1;
for (int i = 0; i < r2; i++) {
curr_sum += a[i].first;
curr_sum += b[i].first;
}
for (int i = 0; i < r1; i++) {
curr_sum += ab[i].first;
}
for (int i = r2; i < a.size(); i++) {
all.insert(a[i]);
}
for (int i = r2; i < b.size(); i++) {
all.insert(b[i]);
}
for (int i = 0; i < non.size(); i++) {
all.insert(non[i]);
}
for (int i = r1; i < ab.size(); i++) {
all.insert(ab[i]);
}
int add = 0;
while (curr.size() < (m - curr_el)) {
curr_sum += (*all.begin()).first;
curr.insert(*all.begin());
all.erase(all.begin());
}
ans = curr_sum;
for (int i = l; i < min(k, (int)ab.size()); i++) {
curr_sum -= a[r2 - 1].first;
curr_sum -= b[r2 - 1].first;
curr_sum += ab[r1].first;
all.insert(a[r2 - 1]);
all.insert(b[r2 - 1]);
r2--;
if (all.find(ab[r1]) != all.end()) {
all.erase(ab[r1]);
}
if (curr.find(ab[r1]) != curr.end()) {
curr_sum -= ab[r1].first;
curr.erase(ab[r1]);
}
r1++;
curr_el = r2 * 2 + r1;
while (curr.size() < (m - curr_el)) {
curr_sum += (*all.begin()).first;
curr.insert(*all.begin());
all.erase(all.begin());
}
if (!curr.empty() && !all.empty()) {
auto curr_last = curr.end();
curr_last--;
while (!all.empty() && *curr_last > *all.begin()) {
curr_sum -= (*curr_last).first;
curr_sum += (*all.begin()).first;
all.insert(*curr_last);
curr.erase(curr_last);
curr.insert(*all.begin());
all.erase(all.begin());
curr_last = curr.end();
curr_last--;
}
}
if (curr_sum < ans) {
ans = curr_sum;
ans_r1 = r1;
ans_r2 = r2;
}
}
r1 = ans_r1;
r2 = ans_r2;
cout << ans << "\n";
for (int i = 0; i < r1; i++) {
cout << ab[i].second + 1 << " ";
}
for (int i = 0; i < r2; i++) {
cout << a[i].second + 1 << " ";
cout << b[i].second + 1 << " ";
}
set<pair<int, int> > free;
for (int i = r2; i < a.size(); i++) {
free.insert(a[i]);
}
for (int i = r2; i < b.size(); i++) {
free.insert(b[i]);
}
for (int i = 0; i < non.size(); i++) {
free.insert(non[i]);
}
for (int i = r1; i < ab.size(); i++) {
free.insert(ab[i]);
}
curr_el = r2 * 2 + r1;
for (int i = 0; i < (m - curr_el); i++) {
cout << (*free.begin()).second + 1 << " ";
free.erase(free.begin());
}
return 0;
}
| 11 | CPP |
from collections import defaultdict as dd
import sys
input=sys.stdin.readline
#n=int(input())
n,kk=map(int,input().split())
l=[]
ans=0
for i in range(n):
time,a,b=map(int,input().split())
l.append((time,a,b))
l.sort()
la=[]
lb=[]
do=[]
for i in l:
time,a,b=i
if(a and b):
do.append(time)
elif(a):
la.append(time)
elif(b):
lb.append(time)
i=0
j=0
k=0
ca=kk
cb=kk
while ca and cb:
if(i<len(la)):
if(j<len(lb)):
if(k<len(do)):
if(la[i]+lb[j]<=do[k]):
ans+=la[i]
ans+=lb[j]
i+=1
j+=1
ca-=1
cb-=1
else:
ans+=do[k]
k+=1
ca-=1
cb-=1
else:
ans+=la[i]
ans+=lb[j]
i+=1
j+=1
ca-=1
cb-=1
else:
if(k<len(do)):
ans+=do[k]
k+=1
ca-=1
cb-=1
else:
break
else:
if(k<len(do)):
ans+=do[k]
k+=1
ca-=1
cb-=1
else:
break
if(ca):
while ca and i<len(la) and k<len(do):
if(la[i]<=do[k]):
ans+=la[i]
i+=1
ca-=1
else:
ans+=do[k]
k+=1
ca-=1
while ca and i<len(la):
ans+=la[i]
i+=1
ca-=1
while ca and k<len(do):
ans+=do[k]
k+=1
ca-=1
elif(cb):
i=j
la=lb
ca=cb
while ca and i<len(la) and k<len(do):
if(la[i]<=do[k]):
ans+=la[i]
i+=1
ca-=1
else:
ans+=do[k]
k+=1
ca-=1
while ca and i<len(la):
ans+=la[i]
i+=1
ca-=1
while ca and k<len(do):
ans+=do[k]
k+=1
ca-=1
cb=ca
if(ca or cb):
print(-1)
else:
print(ans)
| 11 | PYTHON3 |
#include <bits/stdc++.h>
using namespace std;
int mpow(int base, int exp);
void ipgraph(int n, int m);
void dfs(int u, int par);
const int mod = 1e9 + 7;
struct cmp {
bool operator()(const int& lhs, const int& rhs) const { return lhs < rhs; }
};
int mpow(int base, int exp) {
base %= mod;
int result = 1;
while (exp > 0) {
if (exp & 1) result = ((long long)result * base) % mod;
base = ((long long)base * base) % mod;
exp >>= 1;
}
return result;
}
bool isPrime(int n) {
if (n <= 1) return false;
if (n <= 3) return true;
if (n % 2 == 0 || n % 3 == 0) return false;
for (int i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0) return false;
return true;
}
void solve() {
long long n, k, time;
bool l1, l2;
cin >> n >> k;
vector<int> a1, a2, a3;
for (int i = 0; i < n; i++) {
cin >> time;
cin >> l1 >> l2;
if (l1 & l2) {
a1.push_back(time);
} else if (l1) {
a2.push_back(time);
} else if (l2) {
a3.push_back(time);
}
}
if (a1.size() + a2.size() < k || a1.size() + a3.size() < k) {
cout << -1;
return;
}
sort(a1.begin(), a1.end());
sort(a2.begin(), a2.end());
sort(a3.begin(), a3.end());
int p1 = 0, p2 = 0, p3 = 0;
int cnt = 0, res = 0;
int s1 = a1.size(), s2 = a2.size(), s3 = a3.size();
while (cnt < k && p1 < s1 && p2 < s2 && p3 < s3) {
if (a1[p1] < a2[p2] + a3[p3]) {
res += a1[p1];
p1++;
} else {
res += a2[p2] + a3[p3];
p2++;
p3++;
}
cnt++;
}
while (cnt < k && p1 < s1) {
res += a1[p1];
p1++;
cnt++;
}
while (cnt < k && p2 < s2 && p3 < s3) {
res += a2[p2] + a3[p3];
p2++;
p3++;
cnt++;
}
cout << res;
}
int main() {
ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
int t = 1;
solve();
cout << "\n";
return 0;
}
| 11 | CPP |
import sys
from collections import deque, defaultdict
input = sys.stdin.buffer.readline
n, k = map(int, input().split())
al, bl, cc = [], [], []
for _ in range(n):
t, a, b = map(int, input().split())
if a and not b: al.append(t)
elif not a and b: bl.append(t)
elif a and b: cc.append(t)
al.sort(); bl.sort()
for i in range(min(len(al), len(bl))):
cc.append(al[i]+bl[i])
cc.sort()
if len(cc) < k: print(-1)
else: print(sum(cc[0:k]))
| 11 | PYTHON3 |
n,k=map(int, input().split())
tab=[tuple(map(int,input().split())) for _ in range(n)]
both=[tabi[0] for tabi in tab if tabi[1:]==(1,1)]
both.sort()
alice=[tabi[0] for tabi in tab if tabi[1:]==(1,0)]# tabi[1]==1 and tabi[2]==0]
bob=[tabi[0] for tabi in tab if tabi[1:]==(0,1)]
alice.sort()
bob.sort()
ab=[alice[i]+bob[i] for i in range(min(len(alice),len(bob)))]
both+=ab
both.sort()
if len(both)<k:
print(-1)
else:print(sum(both[:k]))
| 11 | PYTHON3 |
n,k = [int(x) for x in input().strip().split()]
vec = []
for _ in range(n):
vec.append([int(x) for x in input().split()])
vec.sort()
f1 = f2 = f3 = 0
minsum = 0
count = 0
min_12 = min_3 = 0
flag12 = flag3 = True
while ((f3 <= n-1 or (f1 <= n-1 and f2 <= n-1)) and count < k):
while f3 <= n-1:
if vec[f3][1] == 1 and vec[f3][2] == 1:
break
f3 += 1
if f3 <= n-1:
min_3 = vec[f3][0]
else:
flag3 = False
while f2 <= n-1:
if vec[f2][1] == 1 and vec[f2][2] == 0:
break
f2 += 1
while f1 <= n-1:
if vec[f1][1] == 0 and vec[f1][2] == 1:
break
f1 += 1
if f1 <= n-1 and f2 <= n-1:
min_12 = vec[f1][0] + vec[f2][0]
else:
flag12 = False
if flag12 and flag3:
count +=1
if min_3 <= min_12:
f3 += 1
minsum += min_3
else:
f1 += 1
f2 += 1
minsum += min_12
elif flag12:
count += 1
f1 += 1
f2 += 1
minsum += min_12
elif flag3:
count += 1
f3 += 1
minsum += min_3
if count == k:
print(minsum)
else:
print(-1)
| 11 | PYTHON3 |
n,k=map(int,input().split())
l1=[]
l2=[]
l3=[]
ac,bc=0,0
for i in range(n):
t,a,b=map(int,input().split())
if(a==1 and b==1):
l1.append(t)
ac+=1
bc+=1
elif(a==1 and b==0):
l2.append(t)
ac+=1
elif(a==0 and b==1):
l3.append(t)
bc+=1
if(ac<k or bc<k):
print(-1)
else:
l2.sort()
l3.sort()
ans=0
for i in range(min(len(l2),len(l3))):
l1.append(l2[i]+l3[i])
l1.sort()
for i in range(k):
ans+=l1[i]
print(ans)
| 11 | PYTHON3 |
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, k;
cin >> n >> k;
vector<pair<int, pair<int, int>>> v;
for (int i = 0; i < n; i++) {
int t, a, b;
cin >> t >> a >> b;
v.push_back({t, {a, b}});
}
vector<int> f;
vector<pair<int, pair<int, int>>> l;
vector<pair<int, pair<int, int>>> r;
for (auto xx : v) {
if ((xx.second.second == 1) && (xx.second.first == 1)) {
f.push_back(xx.first);
}
if ((xx.second.second == 0) && (xx.second.first == 1)) {
l.push_back(xx);
}
if ((xx.second.second == 1) && (xx.second.first == 0)) {
r.push_back(xx);
}
}
sort(l.begin(), l.end());
sort(r.begin(), r.end());
int id1 = 0, id2 = 0;
while ((id1 < l.size()) && (id2 < r.size())) {
f.push_back(l[id1].first + r[id2].first);
id1++, id2++;
}
sort(f.begin(), f.end());
long long sum = 0;
if (f.size() < k) {
cout << "-1"
<< "\n";
return 0;
}
for (int i = 0; i < k; i++) {
sum += f[i];
}
cout << sum << "\n";
}
| 11 | CPP |
from sys import stdin
from collections import deque
# https://codeforces.com/contest/1354/status/D
mod = 10**9 + 7
import sys
import random
# sys.setrecursionlimit(10**6)
from queue import PriorityQueue
from collections import Counter as cc
# def rl():
# return [int(w) for w in stdin.readline().split()]
from bisect import bisect_right
from bisect import bisect_left
from collections import defaultdict
from math import sqrt,factorial,gcd,log2,inf,ceil
# map(int,input().split())
# # l = list(map(int,input().split()))
# from itertools import permutations
import heapq
# input = lambda: sys.stdin.readline().rstrip()
input = lambda : sys.stdin.readline().rstrip()
from sys import stdin, stdout
from heapq import heapify, heappush, heappop
from itertools import permutations
from math import factorial as f
# def ncr(x, y):
# return f(x) // (f(y) * f(x - y))
def ncr(n, r, p):
num = den = 1
for i in range(r):
num = (num * (n - i)) % p
den = (den * (i + 1)) % p
return (num * pow(den,
p - 2, p)) % p
import sys
# input = sys.stdin.readline
# LCA
# def bfs(na):
#
# queue = [na]
# boo[na] = True
# level[na] = 0
#
# while queue!=[]:
#
# z = queue.pop(0)
#
# for i in hash[z]:
#
# if not boo[i]:
#
# queue.append(i)
# level[i] = level[z] + 1
# boo[i] = True
# dp[i][0] = z
#
#
#
# def prec(n):
#
# for i in range(1,20):
#
# for j in range(1,n+1):
# if dp[j][i-1]!=-1:
# dp[j][i] = dp[dp[j][i-1]][i-1]
#
#
# def lca(u,v):
# if level[v] < level[u]:
# u,v = v,u
#
# diff = level[v] - level[u]
#
#
# for i in range(20):
# if ((diff>>i)&1):
# v = dp[v][i]
#
#
# if u == v:
# return u
#
#
# for i in range(19,-1,-1):
# # print(i)
# if dp[u][i] != dp[v][i]:
#
# u = dp[u][i]
# v = dp[v][i]
#
#
# return dp[u][0]
#
# dp = []
#
#
# n = int(input())
#
# for i in range(n + 10):
#
# ka = [-1]*(20)
# dp.append(ka)
# class FenwickTree:
# def __init__(self, x):
# """transform list into BIT"""
# self.bit = x
# for i in range(len(x)):
# j = i | (i + 1)
# if j < len(x):
# x[j] += x[i]
#
# def update(self, idx, x):
# """updates bit[idx] += x"""
# while idx < len(self.bit):
# self.bit[idx] += x
# idx |= idx + 1
#
# def query(self, end):
# """calc sum(bit[:end])"""
# x = 0
# while end:
# x += self.bit[end - 1]
# end &= end - 1
# return x
#
# def find_kth_smallest(self, k):
# """Find largest idx such that sum(bit[:idx]) <= k"""
# idx = -1
# for d in reversed(range(len(self.bit).bit_length())):
# right_idx = idx + (1 << d)
# if right_idx < len(self.bit) and k >= self.bit[right_idx]:
# idx = right_idx
# k -= self.bit[idx]
# return idx + 1
# import sys
# def rs(): return sys.stdin.readline().strip()
# def ri(): return int(sys.stdin.readline())
# def ria(): return list(map(int, sys.stdin.readline().split()))
# def prn(n): sys.stdout.write(str(n))
# def pia(a): sys.stdout.write(' '.join([str(s) for s in a]))
#
#
# import gc, os
#
# ii = 0
# _inp = b''
#
#
# def getchar():
# global ii, _inp
# if ii >= len(_inp):
# _inp = os.read(0, 100000)
# gc.collect()
# ii = 0
# if not _inp:
# return b' '[0]
# ii += 1
# return _inp[ii - 1]
#
#
# def input():
# c = getchar()
# if c == b'-'[0]:
# x = 0
# sign = 1
# else:
# x = c - b'0'[0]
# sign = 0
# c = getchar()
# while c >= b'0'[0]:
# x = 10 * x + c - b'0'[0]
# c = getchar()
# if c == b'\r'[0]:
# getchar()
# return -x if sign else x
# fenwick Tree
# n,q = map(int,input().split())
#
#
# l1 = list(map(int,input().split()))
#
# l2 = list(map(int,input().split()))
#
# bit = [0]*(10**6 + 1)
#
# def update(i,add,bit):
#
# while i>0 and i<len(bit):
#
# bit[i]+=add
# i = i + (i&(-i))
#
#
# def sum(i,bit):
# ans = 0
# while i>0:
#
# ans+=bit[i]
# i = i - (i & ( -i))
#
#
# return ans
#
# def find_smallest(k,bit):
#
# l = 0
# h = len(bit)
# while l<h:
#
# mid = (l+h)//2
# if k <= sum(mid,bit):
# h = mid
# else:
# l = mid + 1
#
#
# return l
#
#
# def insert(x,bit):
# update(x,1,bit)
#
# def delete(x,bit):
# update(x,-1,bit)
# fa = set()
#
# for i in l1:
# insert(i,bit)
#
#
# for i in l2:
# if i>0:
# insert(i,bit)
#
# else:
# z = find_smallest(-i,bit)
#
# delete(z,bit)
#
#
# # print(bit)
# if len(set(bit)) == 1:
# print(0)
# else:
# for i in range(1,n+1):
# z = find_smallest(i,bit)
# if z!=0:
# print(z)
# break
#
# service time problem
# def solve2(s,a,b,hash,z,cnt):
# temp = cnt.copy()
# x,y = hash[a],hash[b]
# i = 0
# j = len(s)-1
#
# while z:
#
# if s[j] - y>=x-s[i]:
# if temp[s[j]]-1 == 0:
# j-=1
# temp[s[j]]-=1
# z-=1
#
#
# else:
# if temp[s[i]]-1 == 0:
# i+=1
#
# temp[s[i]]-=1
# z-=1
#
# return s[i:j+1]
#
#
#
#
#
# def solve1(l,s,posn,z,hash):
#
# ans = []
# for i in l:
# a,b = i
# ka = solve2(s,a,b,posn,z,hash)
# ans.append(ka)
#
# return ans
#
# def consistent(input, window, min_entries, max_entries, tolerance):
#
# l = input
# n = len(l)
# l.sort()
# s = list(set(l))
# s.sort()
#
# if min_entries<=n<=max_entries:
#
# if s[-1] - s[0]<window:
# return True
# hash = defaultdict(int)
# posn = defaultdict(int)
# for i in l:
# hash[i]+=1
#
# z = (tolerance*(n))//100
# poss_window = set()
#
#
# for i in range(len(s)):
# posn[i] = l[i]
# for j in range(i+1,len(s)):
# if s[j]-s[i] == window:
# poss_window.add((s[i],s[j]))
#
# if poss_window!=set():
# print(poss_window)
# ans = solve1(poss_window,s,posn,z,hash)
# print(ans)
#
#
# else:
# pass
#
# else:
# return False
#
#
#
#
# l = list(map(int,input().split()))
#
# min_ent,max_ent = map(int,input().split())
# w = int(input())
# tol = int(input())
# consistent(l, w, min_ent, max_ent, tol)
# t = int(input())
#
# for i in range(t):
#
# n,x = map(int,input().split())
#
# l = list(map(int,input().split()))
#
# e,o = 0,0
#
# for i in l:
# if i%2 == 0:
# e+=1
# else:
# o+=1
#
# if e+o>=x and o!=0:
# z = e+o - x
# if z == 0:
# if o%2 == 0:
# print('No')
# else:
# print('Yes')
# continue
# if o%2 == 0:
# o-=1
# z-=1
# if e>=z:
# print('Yes')
# else:
# z-=e
# o-=z
# if o%2!=0:
# print('Yes')
# else:
# print('No')
#
# else:
#
# if e>=z:
# print('Yes')
# else:
# z-=e
# o-=z
# if o%2!=0:
# print('Yes')
# else:
# print('No')
# else:
# print('No')
#
#
#
#
#
#
#
# def dfs(n):
# boo[n] = True
# dp2[n] = 1
# for i in hash[n]:
# if not boo[i]:
#
# dfs(i)
# dp2[n] += dp2[i]
#
#
# n = int(input())
# x = 0
# l = list(map(int,input().split()))
# for i in range(n):
#
# x = l[i]|x
#
# z = list(bin(x)[2:])
# ha = z.copy()
# k = z.count('1')
# ans = 0
# # print(z)
# cnt = 0
# for i in range(20):
#
#
# maxi = 0
# idx = -1
#
# for j in range(n):
# k = bin(l[j])[2:]
# k = '0'*(len(z) -len(k)) + k
# cnt = 0
# for i in range(len(z)):
# if k[i] == z[i] == '1':
# cnt+=1
#
# maxi = max(maxi,cnt)
# if maxi == cnt:
# idx = j
# if idx!=-1:
#
# k = bin(l[idx])[2:]
# k = '0'*(len(z) -len(k)) + k
#
# for i in range(len(z)):
# if k[i] == z[i] == '1':
# z[i] = '0'
# l[idx] = 0
#
#
# ans = 0
# for i in range(len(z)):
# if z[i] == '0' and ha[i] == '1':
# ans+=1
# flip = 0
# for i in range(ans):
# flip+=2**i
#
#
#
# print(flip)
# def search(k,l,low):
#
# high = len(l)-1
# z = bisect_left(l,k,low,high)
#
# return z
#
#
#
#
#
#
# n,x = map(int,input().split())
#
# l = list(map(int,input().split()))
#
# prefix = [0]
# ha = [0]
# for i in l:
# prefix.append(i + prefix[-1])
# ha.append((i*(i+1))//2 + ha[-1])
# fin = 0
# print(prefix)
# for i in range(n):
# ans = 0
# if l[i]<x:
#
#
# if prefix[-1]-prefix[i]>=x:
#
# z = search(x+prefix[i],prefix,i+1)
# print(z)
# z+=i+1
# k1 = x-(prefix[z-1]-prefix[i])
# ans+=ha[z-1]
# ans+=(k1*(k1+1))//2
#
#
# else:
# z1 = x - (prefix[-1]-prefix[i])
# z = search(z1,prefix,1)
#
# k1 = x-prefix[z-1]
# ans+=ha[z-1]
# ans+=(k1*(k1+1))//2
#
#
#
#
# elif l[i]>x:
# z1 = ((l[i])*(l[i]+1))//2
# z2 = ((l[i]-x)*(l[i]-x+1))//2
# ans+=z1-z2
# else:
# ans+=(x*(x+1))//2
# t = int(input())
#
# for _ in range(t):
#
# s = list(input())
# ans = [s[0]]
#
# for i in range(1,len(s)-1,2):
# ans.append(s[i])
#
# ans.append(s[-1])
# print(''.join(ans))
#
#
#
# t = int(input())
#
# for _ in range(t):
#
# n = int(input())
# l = list(map(int,input().split()))
# ans = 0
# for i in range(n):
# if l[i]%2!=i%2:
# ans+=1
#
# if ans%2 == 0:
# print(ans//2)
# else:
# print(-1)
# t = int(input())
#
# for _ in range(t):
#
# n,k = map(int,input().split())
# s = input()
#
#
# ans = 0
# ba = []
# for i in range(n):
# if s[i] == '1':
# ba.append(i)
# if ba == []:
# for i in range(0,n,k+1):
# ans+=1
#
# print(ans)
# continue
#
# i = s.index('1')
# c = 0
# for x in range(i-1,-1,-1):
# if c == k:
# c = 0
# ans+=1
# else:
# c+=1
#
#
# while i<len(s):
# count = 0
# dis = 0
# while s[i] == '0':
# dis+=1
# if dis == k:
# dis = 0
# count+=1
# if dis<k and s[i] == '1':
# count-=1
# break
# i+=1
# if i == n:
# break
# i+=1
#
# print(ans)
#
#
#
#
# q1
# def poss1(x):
# cnt = 1
# mini = inf
# for i in l:
# if cnt%2 != 0:
# cnt+=1
# else:
# if i<=x:
# cnt+=1
# mini = min()
# if cnt == k:
# return
#
# return -1
#
#
#
#
# def poss2(x):
# cnt = 1
# for i in l:
# if cnt%2 == 0:
# cnt+=1
# else:
# if i<=x:
# cnt+=1
# if cnt == k:
# return
#
# return -1
#
#
#
# n,k = map(int,input().split())
# l = list(map(int,input().split()))
#
# z1 = min(l)
# z2 = max(l)
# t = int(input())
#
# for _ in range(t):
#
# n,k = map(int,input().split())
# l = list(map(int,input().split()))
#
# for i in range(n):
# z = l[i]%k
#
# if z!=0:
#
# l[i] = k-z
# else:
# l[i] = 0
#
# l.sort()
# count = 0
# ans = 0
# x = 0
# print(l)
# for i in range(n):
#
# z = l[i]
# if z == 0:
# continue
# if x>z:
# z2 = ceil((x-l[i])/k)
# z1 = l[i] + k*z2
# # print(x,z1)
# ans += z1-x + 1
# x = z1+1
# elif z == x:
# ans+=1
# x+=1
# else:
#
# ans += z-x + 1
# x = z+1
# # print(i,x)
# print(ans)
#
#
#
# print(ans)
n,k = map(int,input().split())
ha = k
la1 = []
la2 = []
la3 = []
for i in range(n):
t,a,b = map(int,input().split())
if a == 1 and b == 0:
la1.append(t)
elif a == 0 and b == 1:
la2.append(t)
elif a == 1 and b == 1:
la3.append(t)
la1.sort()
la2.sort()
la3.sort()
ans = 0
count1 = 0
count2 = 0
i,j,k = 0,0,0
z = max(len(la1),len(la2),len(la3))
# print(la1,la2,la3)
while True:
if i>=z and j>=z and k>=z:
break
if count1 >= ha and count2>=ha:
break
t1,t2,t3 = 10**18,10**18,10**18
try:
t1 = la1[i]
except:
pass
try:
t2 = la2[j]
except:
pass
try:
t3 = la3[k]
except:
pass
if count1>=ha and count2>=ha:
break
elif count1<ha and count2<ha:
if t1+t2<=t3:
count1+=1
count2+=1
ans+=t1+t2
i+=1
j+=1
else:
count1+=1
count2+=1
ans+=t3
k+=1
elif count1<ha and count2>=ha:
if t1<=t3:
i+=1
ans+=t1
else:
k+=1
ans+=t3
elif count2<ha and count1>=ha:
if t2<=t3:
j+=1
ans+=t2
else:
k+=1
ans+=t3
if ans>=10**18:
print(-1)
else:
print(ans)
| 11 | PYTHON3 |
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time
# sys.setrecursionlimit(5*10**5)
inf = 10**20
mod = 10**9 + 7
def LI(): return list(map(int, input().split()))
def II(): return int(input())
def LS(): return list(input().split())
def S(): return input()
def main():
n, k = LI()
tab = [LI() for _ in range(n)]
both = list()
only_a = list()
only_b = list()
for t, a, b in tab:
if a and b:
both.append(t)
elif a:
only_a.append(t)
elif b:
only_b.append(t)
m = min(len(only_a), len(only_b))
only_b.sort()
only_a.sort()
for i in range(m):
tmp = only_b[i] + only_a[i]
both.append(tmp)
both.sort()
if len(both) < k:
return -1
return sum(both[:k])
print(main()) | 11 | PYTHON3 |
#!/usr/bin/env python
import os
import sys
from io import BytesIO, IOBase
from bisect import bisect_left,bisect_right
import threading
from collections import Counter,defaultdict
arr=[]
def main():
for _ in range(1):
n,k=map(int,input().split())
ar3=[]
ar1=[]
ar2=[]
for i in range(n):
a,b,c=map(int,input().split())
if b==c==1:
ar3.append(a)
else:
if b==1:
ar1.append(a)
if c==1:
ar2.append(a)
t=2*max(0,k-len(ar3))+len(ar3)
if len(ar3)+len(ar1)<k or len(ar3)+len(ar2)<k:
print(-1)
else:
ar3.sort()
ar1.sort()
ar2.sort()
# print(ar1,ar2,ar3)
pt1=pt2=0
i1=0
i2=0
i3=0
ans=0
m_=0
while i1<len(ar1) and i2<len(ar2) and i3<len(ar3):
if ar1[i1] + ar2[i2] <ar3[i3]:
ans=ans+ar1[i1]+ar2[i2]
i1+=1
i2+=1
else:
ans=ans+ar3[i3]
i3+=1
pt1+=1
pt2+=1
if pt1==pt2==k:
break
# print(pt1,pt2,i1,i2,i3)
if i2>=len(ar2):
i1,i2=i2,i1
ar1,ar2=ar2,ar1
while pt1<k:
if i1<len(ar1) and i3<len(ar3) and ar3[i3]<ar1[i1]:
ans+=ar3[i3]
i3+=1
pt2+=1
elif i1<len(ar1) :
ans+=ar1[i1]
i1+=1
else:
ans+=ar3[i3]
i3+=1
pt2+=1
pt1+=1
while pt2<k:
if i1<len(ar1) and i3<len(ar3) and ar3[i3]<ar1[i1]:
ans+=ar3[i3]
i3+=1
elif i2<len(ar2) :
ans+=ar2[i2]
i2+=1
else:
ans+=ar3[i3]
i3+=1
pt2+=1
print(ans)
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
if __name__ == "__main__":
main() | 11 | PYTHON3 |
def binary(a,start,end,e):
mid=(start+end)//2
if a[mid]==e:
return mid
elif a[mid]>e:
end=mid-1
else:
start=mid+1
if start<=end:
return binary(a,start,end,e)
else:
return start
n,k=map(int,input().split())
p=[]
al=[]
bo=[]
for j in range(n):
a,b,c=map(int,input().split())
if b==1 and c==1:
p.append(a)
elif b==1 and c==0:
al.append(a)
elif b==0 and c==1:
bo.append(a)
al.sort()
bo.sort()
p.sort()
if p!=[]:
while al!=[] and bo!=[]:
v=al[0]+bo[0]
q=binary(p,0,len(p)-1,v)
p.insert(q,v)
del al[0]
del bo[0]
else:
while al!=[] and bo!=[]:
v=al[0]+bo[0]
p.append(v)
del al[0]
del bo[0]
if len(p)<k:
print(-1)
else:
print(sum(p[:k]))
| 11 | PYTHON3 |
#include <bits/stdc++.h>
#pragma GCC optimize("02")
#pragma G++ optimize("03")
using namespace std;
const int N = 2e5 + 5;
int n, k, type1[N], type2[N], type3[N];
int main() {
scanf("%d%d", &n, &k);
int cnt1 = 0, cnt2 = 0, cnt3 = 0;
for (int i = 1; i <= n; i++) {
int val, a, b;
scanf("%d%d%d", &val, &a, &b);
if (!a && !b) continue;
if (a && b) type1[++cnt1] = val;
if (a && !b) type2[++cnt2] = val;
if (!a && b) type3[++cnt3] = val;
}
sort(type1 + 1, type1 + 1 + cnt1);
sort(type2 + 1, type2 + 1 + cnt2);
sort(type3 + 1, type3 + 1 + cnt3);
for (int i = 1; i <= min(cnt2, cnt3); i++)
type1[++cnt1] = type2[i] + type3[i];
sort(type1 + 1, type1 + 1 + cnt1);
if (cnt1 < k)
puts("-1");
else {
int res = 0;
for (int i = 1; i <= k; i++) res += type1[i];
printf("%d\n", res);
}
return 0;
}
| 11 | CPP |
# from bisect import bisect_left
# TC = int(input())
# for tc in range(TC):
N, K = map(int, input().split())
T = []
A = []
B = []
O = []
for b in range(N):
v, a, b = map(int, input().split())
if a == 1 and b == 1:
T.append(v)
elif a == 1:
A.append(v)
elif b == 1:
B.append(v)
else:
O.append(v)
A.sort()
B.sort()
S = []
for i in range(min(len(A),len(B))):
S.append(A[i]+B[i])
R = S + T
if len(R) >= K:
R.sort()
print(sum(R[:K]))
else:
print(-1)
| 11 | PYTHON3 |
n, k = [int(i) for i in input().split()]
doub = []; a = []; b = []
for i in range(n):
ti, ai, bi = [int(i) for i in input().split()]
if ai and bi:
doub.append(ti)
elif ai:
a.append(ti)
elif bi:
b.append(ti)
doub.sort(); a.sort(); b.sort()
# print(doub, a, b, sep="\n")
time = 0
i = 0; j = 0
while i+j < k:
if (i < len(doub)):
db = doub[i]
else:
db = 100000
if (j < len(a) and j < len(b)):
sing = a[j] + b[j]
else:
sing = 100000
if (db <= sing):
time += db
i += 1
else:
time += sing
j += 1
if (len(doub) + min(len(a), len(b))) >= k:
print(time)
else:
print(-1)
| 11 | PYTHON3 |
import sys
n, k = [int(e) for e in input().split(' ')]
books = list()
books_map = dict()
for i in range(n):
t, a, b = [int(e) for e in input().split(' ')]
books.append((t, a, b, i))
books_map[i] = (t, a, b)
books = sorted(books, key = lambda x : x[0] * (1 if x[1] == 1 else 1e7))
alice_pay_time = 0
alice_liked_books = list()
for book in books:
if len(alice_liked_books) >= k:
break
if book[1] == 1 and book[2] == 0:
alice_pay_time += book[0]
alice_liked_books.append(book[3])
books = sorted(books, key = lambda x : x[0] * (1 if x[2] == 1 else 1e7))
bob_pay_time = 0
bob_liked_books = list()
for book in books:
if len(bob_liked_books) >= k:
break
if book[2] == 1 and book[1] == 0:
bob_pay_time += book[0]
bob_liked_books.append(book[3])
books = sorted(books, key = lambda x : x[0] * (1 if x[1] == 1 and x[2] == 1 else 1e7))
pay_time = alice_pay_time + bob_pay_time
alice_liked_book_count = len(alice_liked_books)
bob_liked_book_count = len(bob_liked_books)
for book in books:
if book[1] == 1 and book[2] == 1:
if alice_liked_book_count < k or bob_liked_book_count < k:
pay_time += book[0]
alice_liked_book_count += 1
bob_liked_book_count += 1
if alice_liked_book_count > k:
pay_time -= books_map[alice_liked_books[-1]][0]
alice_liked_books.pop()
alice_liked_book_count = k
if bob_liked_book_count > k:
pay_time -= books_map[bob_liked_books[-1]][0]
bob_liked_books.pop()
bob_liked_book_count = k
elif len(alice_liked_books) == 0 or len(bob_liked_books) == 0:
break
elif book[0] < books_map[alice_liked_books[-1]][0] + books_map[bob_liked_books[-1]][0]:
pay_time -= books_map[alice_liked_books[-1]][0]
pay_time -= books_map[bob_liked_books[-1]][0]
pay_time += book[0]
alice_liked_books.pop()
bob_liked_books.pop()
if alice_liked_book_count >= k and bob_liked_book_count >= k:
print(pay_time)
else:
print(-1)
| 11 | PYTHON3 |
n,k=map(int,input().split())
l,l1,l2=[],[],[]
for i in range(n):
t,a,b=map(int,input().split())
if a==1 and b==1:
l.append(t)
if a==1 and b==0:
l1.append(t)
if a==0 and b==1:
l2.append(t)
l1.sort()
l2.sort()
for i in range(min(len(l1),len(l2))):
l.append(l1[i]+l2[i])
l.sort()
if len(l)<k:
print(-1)
else:
print(sum(l[:k]))
| 11 | PYTHON3 |
import sys
def swap(x, y, a):
temp = a[x]
a[x] = a[y]
a[y] = temp
return a
def solve():
return None
def main():
q = []
for line in sys.stdin.readlines():
q.append(line)
for i in range(len(q)):
q[i] = q[i].rstrip().split(' ')
q[i] = [int(x) for x in q[i]]
k = q[0][1]
# combining the ones that we can combine
# get rid of the ones where both people dont like reading
both = [] # keeps track of books both people like
only_left = [] # only left person likes
only_right = [] # only right person likes
for i in range(1,len(q)):
if q[i][1] == 1 and q[i][2] == 1:
both.append(q[i][0])
elif q[i][1] == 1 and q[i][2] == 0:
only_left.append(q[i][0])
elif q[i][1] == 0 and q[i][2] == 1:
only_right.append(q[i][0])
# print(both)
# print(only_left)
# print(only_right)
only_left.sort()
only_right.sort()
for i in range(min(len(only_left), len(only_right))):
both.append(only_left[i] + only_right[i])
both.sort()
if len(both) < k:
print(-1)
else:
# print(both)
print(sum(both[:k]))
# print(k, q)
if __name__ == '__main__':
main() | 11 | PYTHON3 |
line = input()
n, m, k = [int(i) for i in line.split(' ')]
books, allL, aliceL, bobL, other =list(range(1, n + 1)), [], [], [], []
ts = [[] for _ in range(n + 1)]
for i in range(n):
line = input()
t, a, b = [int(j) for j in line.split(' ')]
ts[i + 1] = [t, a, b]
if a == 1 and b == 1:
allL.append(i + 1)
elif a == 1:
aliceL.append(i + 1)
elif b == 1:
bobL.append(i + 1)
else:
other.append(i + 1)
if len(allL) + min(len(aliceL), len(bobL)) < k or (len(allL) < k and 2 * (k - len(allL)) > m - len(allL)) :
print(-1)
exit()
books.sort(key=lambda x: (ts[x][0], -ts[x][2]*ts[x][1]))
allL.sort(key=lambda x: (ts[x][0], -ts[x][2]*ts[x][1]))
aliceL.sort(key=lambda x: (ts[x][0], -ts[x][2]*ts[x][1]))
bobL.sort(key=lambda x: (ts[x][0], -ts[x][2]*ts[x][1]))
other.sort(key=lambda x: (ts[x][0], -ts[x][2]*ts[x][1]))
x = max(2 * k - m, 0, k - min(len(aliceL), len(bobL)), m - len(aliceL) - len(bobL) - len(other))
cura, curb, curo, cur = max(0, k - x), max(0, k - x), 0, sum(ts[i][0] for i in allL[:x])
cur += sum(ts[i][0] for i in aliceL[:cura]) + sum(ts[i][0] for i in bobL[:curb])
while cura + x + curb + curo < m:
an = ts[aliceL[cura]][0] if cura < len(aliceL) else 9999999999
bn = ts[bobL[curb]][0] if curb < len(bobL) else 9999999999
on = ts[other[curo]][0] if curo < len(other) else 9999999999
cur += min(an, bn, on)
if an <= bn and an <= on:
cura += 1
elif bn <= an and bn <= on:
curb += 1
else:
curo += 1
res, a, b, o = cur, cura, curb, curo
for i in range(x + 1, len(allL) + 1): #都喜欢的长度
cur += ts[allL[i - 1]][0]
if cura > 0:
cura -= 1
cur -= ts[aliceL[cura]][0]
if curb > 0:
curb -= 1
cur -= ts[bobL[curb]][0]
if curo > 0:
curo -= 1
cur -= ts[other[curo]][0]
while cura + i + curb + curo < m:
an = ts[aliceL[cura]][0] if cura < len(aliceL) else 9999999999
bn = ts[bobL[curb]][0] if curb < len(bobL) else 9999999999
on = ts[other[curo]][0] if curo < len(other) else 9999999999
cur += min(an, bn, on)
if an <= bn and an <= on:
cura += 1
elif bn <= an and bn <= on:
curb += 1
else:
curo += 1
if res > cur:
res,x, a, b, o = cur,i, cura, curb, curo
print(res)
for i in range(x):
print(allL[i], end=' ')
for i in range(a):
print(aliceL[i], end = ' ')
for i in range(b):
print(bobL[i], end = ' ')
for i in range(o):
print(other[i], end = ' ')
| 11 | PYTHON3 |
n,k = map(int,input().split())
a=[]
b=[]
c=[]
d=[]
for i in range(n):
x,y,z = map(int,input().split())
if y==0 and z==0:
d.append(x)
elif y==1 and z==1:
a.append(x)
elif y==0 and z==1:
c.append(x)
else:
b.append(x)
b.sort()
c.sort()
m=min(len(b),len(c))
for i in range(m):
a.append(b[i]+c[i])
a.sort()
if len(a)<k:
print("-1")
else:
print(sum(a[:k])) | 11 | PYTHON3 |
#include <bits/stdc++.h>
using namespace std;
using lint = long long int;
using pint = pair<int, int>;
using plint = pair<lint, lint>;
struct fast_ios {
fast_ios() {
cin.tie(0);
ios::sync_with_stdio(false);
cout << fixed << setprecision(20);
};
} fast_ios_;
template <typename T>
istream &operator>>(istream &is, vector<T> &vec) {
for (auto &v : vec) is >> v;
return is;
}
template <typename T>
bool chmax(T &m, const T q) {
if (m < q) {
m = q;
return true;
} else
return false;
}
template <typename T>
bool chmin(T &m, const T q) {
if (q < m) {
m = q;
return true;
} else
return false;
}
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
template <class c>
struct rge {
c b, e;
};
template <class c>
rge<c> range(c i, c j) {
return rge<c>{i, j};
}
template <class c>
auto dud(c *x) -> decltype(cerr << *x, 0);
template <class c>
char dud(...);
struct deb {
~deb() { cerr << endl; }
template <class c>
typename enable_if<sizeof dud<c>(0) != 1, deb &>::type operator<<(c i) {
cerr << boolalpha << i;
return *this;
}
template <class c>
typename enable_if<sizeof dud<c>(0) == 1, deb &>::type operator<<(c i) {
return *this << range(begin(i), end(i));
}
template <class c, class b>
deb &operator<<(pair<b, c> d) {
return *this << "(" << d.first << ", " << d.second << ")";
}
template <class c>
deb &operator<<(rge<c> d) {
*this << "[";
for (auto it = d.b; it != d.e; ++it) *this << ", " + 2 * (it == d.b) << *it;
return *this << "]";
}
};
void err(istream_iterator<string> it) { return; }
template <typename T, typename... Args>
void err(istream_iterator<string> it, T a, Args... args) {
cerr << *it << " = " << a << endl;
err(++it, args...);
}
void solve() {
lint n, k;
cin >> n >> k;
vector<lint> time(n);
vector<lint> alice(n);
vector<lint> bob(n);
priority_queue<int, vector<int>, greater<int>> abra;
priority_queue<int, vector<int>, greater<int>> cadabra;
priority_queue<int, vector<int>, greater<int>> mixed;
for (int i = (0), i_end_ = (n); i < i_end_; i++) {
lint t, a, b;
cin >> t >> a >> b;
time[i] = t;
alice[i] = a;
bob[i] = b;
if (a == 1 && b == 1) {
mixed.push(t);
} else if (a == 1) {
abra.push(t);
} else if (b == 1) {
cadabra.push(t);
}
}
lint ret = 0;
lint cc = 2 * k;
lint s1 = accumulate(begin(alice), end(alice), 0LL);
lint s2 = accumulate(begin(bob), end(bob), 0LL);
if (s1 <= k - 1 || s2 <= k - 1) {
cout << -1 << '\n';
return;
}
while (cc) {
bool ok = 0;
int f = 0;
lint t = INT_MAX;
if (mixed.size() > 0) {
t = mixed.top();
ok = 1;
}
lint t1 = INT_MAX;
lint t2 = INT_MAX;
if (abra.size()) {
t1 = abra.top();
++f;
}
if (cadabra.size()) {
t2 = cadabra.top();
++f;
}
if (!ok && f <= 1) break;
if (t <= t1 + t2) {
ret += t;
mixed.pop();
} else {
ret += t1 + t2;
abra.pop();
cadabra.pop();
}
cc -= 2;
}
cout << ret << '\n';
}
int main() {
int T = 1;
for (int tt = 1; tt <= T; ++tt) {
solve();
}
return 0;
}
lint pow_mod(lint base, lint expo) {
lint ret = 1;
for (; expo;) {
if (expo & 1) ret = (ret * base) % 1000000007;
expo = (expo >> 1);
base = (base * base) % 1000000007;
}
return ret;
}
| 11 | CPP |
# cook your dish here
# input = open('file.txt').readline
n , k = list(map(int , input().split()))
ali = []
bob = []
both = []
ac , bc = 0 , 0
for __ in range(n):
t , ai , bi = list(map(int , input().split()))
if ai == bi and ai == 1:
both.append(t)
ac += 1
bc += 1
elif ai == 1:
ali.append(t)
ac += 1
elif bi == 1:
bob.append(t)
bc += 1
if ac < k or bc < k:
print(-1)
else:
ans = 0
i = 0
both.sort()
ali.sort()
bob.sort()
bbi = 0
ai , bi = 0 , 0
bbl = len(both)
al = len(ali)
bl = len(bob)
while i < k:
if bbi < bbl and ai < al and bi < bl:
age = both[bbi]
pic = ali[ai] + bob[bi]
if age < pic:
ans += age
# both.pop(0)
bbi += 1
else:
ans += pic
# ali.pop(0)
# bob.pop(0)
ai += 1
bi += 1
elif bbi < bbl:
ans += both[bbi]
bbi += 1
else:
ans += ( ali[ai] + bob[bi] )
ai += 1
bi += 1
i += 1
print(ans) | 11 | PYTHON3 |
n, k = map(int, input().split())
al=[];bob=[];both=[]
for i in range(n):
a,b,c= map(int, input().split())
if(b==1 and c==1):
both.append(a)
elif(b==1):
al.append(a)
elif(c==1):
bob.append(a)
tp=len(both)
la=len(al)
ob=len(bob)
a=la+tp
b=ob+tp
if(a<k or b<k):
print("-1")
else:
both.sort()
al.sort()
bob.sort()
ans=0
c=0;d=0
for i in range(k):
z=20001
m=20001
if(c<tp):
z=both[c]
if(d<la and d<ob):
m=(al[d]+bob[d])
if(z<m):
ans+=z
c+=1
else:
ans+=m
d+=1
print(ans) | 11 | PYTHON3 |
#include <bits/stdc++.h>
using namespace std;
inline long long gcd(long long a, long long b) {
while (b != 0) {
long long c = a % b;
a = b;
b = c;
}
return a < 0 ? -a : a;
}
inline long long lowbit(long long x) { return x & (-x); }
const double PI = 3.14159265358979323846;
const int inf = 0x3f3f3f3f;
const long long INF = 0x3f3f3f3f3f3f3f3f;
const long long mod = 998244353;
inline long long rd() {
long long x = 0, f = 1;
char ch = getchar();
while (ch < '0' || ch > '9') {
if (ch == '-') f = -1;
ch = getchar();
}
while (ch >= '0' && ch <= '9') {
x = (x << 3) + (x << 1) + (ch ^ 48);
ch = getchar();
}
return x * f;
}
const double eps = 1e-6;
const int M = 1e6 + 10;
const int N = 1e6 + 10;
struct MM {
int id, val;
bool friend operator<(const MM& m1, const MM& m2) { return m1.val < m2.val; }
};
MM a[N], b[N], c[N], d[N];
int x1 = 0, x2 = 0, x3 = 0, x4 = 0;
int n, m, k;
vector<int> ans;
MM pp[N];
long long f(int x) {
ans.clear();
long long sum = 0;
if (x > x3 || x + x1 < k || x + x2 < k || 2 * k - x > m) return INF;
for (int i = 1; i <= x; i++) {
sum += c[i].val;
ans.push_back(c[i].id);
}
for (int i = 1; i <= k - x; i++) {
sum += a[i].val;
ans.push_back(a[i].id);
}
for (int i = 1; i <= k - x; i++) {
sum += b[i].val;
ans.push_back(b[i].id);
}
int cnt = 0;
for (int i = max(k - x + 1, 1); i <= x1; i++) {
pp[++cnt] = a[i];
}
for (int i = max(k - x + 1, 1); i <= x2; i++) {
pp[++cnt] = b[i];
}
for (int i = x + 1; i <= x3; i++) {
pp[++cnt] = c[i];
}
for (int i = 1; i <= x4; i++) {
pp[++cnt] = d[i];
}
int res = m - (2 * k - x);
sort(pp + 1, pp + 1 + cnt);
for (int i = 1; i <= res; i++) {
ans.push_back(pp[i].id);
sum += pp[i].val;
}
return sum;
}
int main() {
n = rd(), m = rd(), k = rd();
for (int i = 1; i <= n; i++) {
int t = rd(), aa = rd(), bb = rd();
if (aa && bb)
c[++x3] = {i, t};
else if (aa)
a[++x1] = {i, t};
else if (bb)
b[++x2] = {i, t};
else
d[++x4] = {i, t};
}
sort(a + 1, a + 1 + x1);
sort(b + 1, b + 1 + x2);
sort(c + 1, c + 1 + x3);
sort(d + 1, d + 1 + x4);
if (x3 + x1 < k || x3 + x2 < k) {
cout << -1 << endl;
return 0;
}
int l = 0, r = x3;
int an = l;
while (l + 10 < r) {
int lmid = l + (r - l) / 3, rmid = r - (r - l) / 3;
if (f(lmid) < f(rmid)) {
an = lmid;
r = rmid - 1;
} else {
an = rmid;
l = lmid + 1;
}
}
for (int i = l; i <= r; i++) {
if (f(i) < f(an)) an = i;
}
long long aa = f(an);
if (aa == INF) {
cout << -1 << endl;
return 0;
}
cout << aa << endl;
for (auto& x : ans) {
printf("%d ", x);
}
cout << endl;
}
| 11 | CPP |
#include <bits/stdc++.h>
using namespace std;
struct books {
int t, i;
};
bool cmp(books a, books b) {
if (a.t != b.t) return (a.t < b.t);
return (a.i < b.i);
}
int main() {
int n, m, o, x, y, i, j, t, s, k, l, p = 0, q, e[200001], f[200001];
books a[200001], b[200001], c[200001], d[200001];
long long ans;
cin >> n >> o >> m;
i = 0;
j = 0;
k = 0;
l = 0;
for (q = 1; q <= n; q++) {
cin >> t >> x >> y;
if (x == 1 && y == 1) {
c[k].t = t;
c[k++].i = q;
} else if (x == 1) {
a[i].t = t;
a[i++].i = q;
} else if (y == 1) {
b[j].t = t;
b[j++].i = q;
} else {
d[l].t = t;
d[l++].i = q;
}
}
sort(a, a + i, cmp);
sort(b, b + j, cmp);
sort(c, c + k, cmp);
sort(d, d + l, cmp);
x = 0;
y = 0;
t = 0;
s = 0;
ans = 0;
o -= m;
while (m > 0) {
if (x < i && y < j && t < k) {
if (a[x].t + b[y].t <= c[t].t && o > 0) {
ans += a[x].t + b[y].t;
e[p++] = a[x].i;
e[p++] = b[y].i;
x++;
y++;
o--;
} else {
ans += c[t].t;
e[p++] = c[t].i;
t++;
}
m--;
} else if ((x == i || y == j) && t < k) {
ans += c[t].t;
e[p++] = c[t].i;
t++;
m--;
} else if (t == k && x < i && y < j && o > 0) {
ans += a[x].t + b[y].t;
e[p++] = a[x].i;
e[p++] = b[y].i;
x++;
y++;
m--;
o--;
} else
break;
}
if (m == 0) {
q = 0;
while (o--) {
m = 10001;
if (x < i && a[x].t < m) m = a[x].t;
if (y < j && b[y].t < m) m = b[y].t;
if (t < k && c[t].t < m) m = c[t].t;
if (s < l && d[s].t < m) m = d[s].t;
if (t > 0 && x < i && y < j && c[t - 1].t + m > a[x].t + b[y].t) {
ans += a[x].t + b[y].t;
e[p++] = a[x].i;
e[p++] = b[y].i;
x++;
y++;
ans -= c[t - 1].t;
f[q++] = c[t - 1].i;
t--;
} else {
ans += m;
if (x < i && a[x].t == m) {
e[p++] = a[x].i;
x++;
} else if (y < j && b[y].t == m) {
e[p++] = b[y].i;
y++;
} else if (t < k && c[t].t == m) {
e[p++] = c[t].i;
t++;
} else if (s < l && d[s].t == m) {
e[p++] = d[s].i;
s++;
}
}
}
cout << ans << endl;
sort(e, e + p);
sort(f, f + q);
y = 0;
for (x = 0; x < p; x++) {
if (y < q && e[x] == f[y])
y++;
else
cout << e[x] << " ";
}
cout << endl;
} else
cout << -1 << endl;
return 0;
}
| 11 | CPP |
s=input()
s1=s.split()
n=int(s1[0])
k=int(s1[1])
import heapq
heap1=[]
heap2=[]
heap3=[]
heapq.heapify(heap1)
heapq.heapify(heap2)
heapq.heapify(heap3)
for i in range(n):
s=input()
s1=s.split()
if int(s1[1])==0 and int(s1[2])==1:
heapq.heappush(heap1,int(s1[0]))
if int(s1[1])==1 and int(s1[2])==0:
heapq.heappush(heap2,int(s1[0]))
if int(s1[1])==1 and int(s1[2])==1:
heapq.heappush(heap3,int(s1[0]))
sum1=0
while ((heap1 and heap2) or heap3) and k>0:
if heap1 and heap2:
c1=heapq.heappop(heap1)
c2=heapq.heappop(heap2)
else:
c1=1e10
c2=1e10
if heap3:
c3=heapq.heappop(heap3)
else:
c3=1e10
if c3<(c2+c1):
sum1=sum1+c3
if c1!=1e10:
heapq.heappush(heap1,c1)
if c2!=1e10:
heapq.heappush(heap2,c2)
else:
sum1=sum1+c2+c1
if c3!=1e10:
heapq.heappush(heap3,c3)
k=k-1
if k>0:
print(-1)
else:
print(sum1)
| 11 | PYTHON3 |
def compute(n, k, arr):
add = 0
both = []
alice = []
bob = []
for i in range(n):
if arr[i][1] and arr[i][2]:
both.append(arr[i][0])
elif arr[i][1]:
alice.append(arr[i][0])
elif arr[i][2]:
bob.append(arr[i][0])
both.sort()
alice.sort()
bob.sort()
#print(alice, bob, both)
if (len(alice)+len(both) < k) or (len(both)+len(bob) < k):
return -1
else:
i, j = 0, 0
n, nn, nnn = len(alice), len(bob), len(both)
for _ in range(k):
if not alice or not bob or j >= n or j > nn or (i < nnn and both[i] <= alice[j] + bob[j]):
add += both[i]
i += 1
else:
add += (alice[j] + bob[j])
j += 1
return add
if __name__ == "__main__":
n, k = map(int, input().split())
arr = []
for _ in range(n):
t, a, b = map(int, input().split())
arr.append([t, a, b])
print(compute(n, k, arr))
| 11 | PYTHON3 |
n,k = map(int,input().split())
aa=[]
bb=[]
l=[]
for _ in range(n):
t,a,b=map(int,input().split())
sum1=0
sum2=0
if a&b:
l.append(t)
elif a==1:
aa.append(t)
elif b==1:
bb.append(t)
bb.sort()
aa.sort()
nn=min(len(aa),len(bb))
for i in range(nn):
l.append(bb[i]+aa[i])
if k> len(l):
print(-1)
else:
l.sort()
sum1=0
for i in range(k):
sum1+=l[i]
print(sum1)
| 11 | PYTHON3 |
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 7;
long long poww(long long a, long long b, long long mod) {
long long ans = 1;
while (b) {
if (b & 1) ans = (ans * a) % mod;
a = (a * a) % mod;
b >>= 1;
}
return ans % mod;
}
int main() {
int n, k;
cin >> n >> k;
vector<int> a;
vector<int> b;
vector<int> c;
vector<int> d;
for (int i = 0; i < n; i++) {
int z, x, y;
cin >> z >> x >> y;
if (x == 1 && y == 1) {
a.push_back(z);
} else if (x == 1) {
b.push_back(z);
} else if (y == 1) {
c.push_back(z);
}
}
if (a.size() + min(b.size(), c.size()) < k) {
cout << -1 << endl;
return 0;
}
sort(b.begin(), b.end());
sort(c.begin(), c.end());
for (int i = 0; i < b.size() && i < c.size(); i++) {
int z = b[i] + c[i];
a.push_back(z);
}
sort(a.begin(), a.end());
int sum = 0;
for (int i = 0; i < k; i++) {
sum += a[i];
}
cout << sum << endl;
}
| 11 | CPP |
from sys import stdin
from collections import defaultdict as dd
from collections import deque as dq
import itertools as it
from math import sqrt, log, log2
from fractions import Fraction
n, k = map(int, input().split())
alike, blike = 0, 0
zero_one, one_zero, one_one, zero_zero = [], [], [], []
for i in range(n):
t, a, b = map(int, input().split())
alike += a
blike += b
if a == 0 and b == 1:
zero_one.append((t, i))
elif a == 1 and b == 0:
one_zero.append((t, i))
elif a== 1 and b== 1:
one_one.append((t, i))
else:
pass
# zero_zero.append((t, i))
if alike < k or blike < k:
print(-1)
exit()
zero_one.sort(key = lambda x: x[0])
one_one.sort(key = lambda x: x[0])
one_zero.sort(key = lambda x: x[0])
# zero_zero.sort(key = lambda x: x[0])
alike, blike = 0, 0
zo, oo, oz, zz = 0, 0, 0, 0
lzo, loo, loz = len(zero_one), len(one_one), len(one_zero)
# lzo, loo, loz, lzz = len(zero_one), len(one_one), len(one_zero), len(zero_zero)
tottime = 0
# books = []
while alike<k or blike<k:
# if oo >= loo and zo >= lzo and oz>=loz:
# break
# lbo = len(books)
# if lbo == m:
if alike <k and blike <k:
if oo>= loo and zo>=lzo and oz>=loz:
print(-1)
exit()
elif zo >= lzo or oz >= loz:
tottime += one_one[oo][0]
# books.append(one_one[oo][1])
oo += 1
elif oo >= loo:
tottime += zero_one[zo][0] + one_zero[oz][0]
# books.append(zero_one[zo][1])
# books.append(zero_one[oz][1])
zo += 1
oz += 1
elif zero_one[zo][0] + one_zero[oz][0] < one_one[oo][0]:
tottime += zero_one[zo][0] + one_zero[oz][0]
# books.append(zero_one[zo][1])
# books.append(zero_one[oz][1])
zo += 1
oz += 1
else:
tottime += one_one[oo][0]
# books.append(one_one[oo][1])
oo += 1
alike += 1
blike += 1
elif alike == k and blike < k:
if oo>=loo and zo>=lzo:
print(-1)
exit()
elif oo >= loo:
tottime += zero_one[zo][0]
# books.append(zero_one[zo][1])
zo += 1
elif zo >= lzo:
tottime += one_one[oo][0]
# books.append(one_one[oo][1])
oo += 1
elif zero_one[zo][0] < one_one[oo][0]:
tottime += zero_one[zo][0]
# books.append(zero_one[zo][1])
zo += 1
else:
tottime += one_one[oo][0]
# books.append(one_one[oo][1])
oo += 1
blike += 1
elif alike <k and blike == k:
if oo>=loo and oz>=loz:
print(-1)
exit()
elif oo>=loo:
tottime += one_zero[oz][0]
# books.append(one_zero[oz][1])
oz += 1
elif oz>= loz:
tottime += one_one[oo][0]
# books.append(one_one[oo][1])
oo += 1
elif one_zero[oz][0] < one_one[oo][0]:
tottime += one_zero[oz][0]
# books.append(one_zero[oz][1])
oz += 1
else:
tottime += one_one[oo][0]
# books.append(one_one[oo][1])
oo += 1
print(tottime)
# print(*books)
| 11 | PYTHON3 |
production = True
import sys, math, collections
def input(input_format = 0, multi = 0):
if multi > 0: return [input(input_format) for i in range(multi)]
else:
next_line = sys.stdin.readline()[:-1]
if input_format >= 10:
use_list = False
input_format = int(str(input_format)[-1])
else: use_list = True
if input_format == 0: formatted_input = [next_line]
elif input_format == 1: formatted_input = list(map(int, next_line.split()))
elif input_format == 2: formatted_input = list(map(float, next_line.split()))
elif input_format == 3: formatted_input = list(next_line)
elif input_format == 4: formatted_input = (lambda x: [x[0], list(map(int, x[1:]))])(next_line.split())
elif input_format == 5: formatted_input = (lambda x: [x[0], list(map(float, x[1:]))])(next_line.split())
elif input_format == 6: formatted_input = next_line.split()
else: formatted_input = [next_line]
return formatted_input if use_list else formatted_input[0]
def out(output_line, output_format = 0, newline = True):
formatted_output = ""
if output_format == 0: formatted_output = str(output_line)
elif output_format == 1: formatted_output = " ".join(map(str, output_line))
elif output_format == 2: formatted_output = "\n".join(map(str, output_line))
print(formatted_output, end = "\n" if newline else "")
def log(*args):
if not production:
print("$$$", end = "")
print(*args)
enum = enumerate
#
# >>>>>>>>>>>>>>> START OF SOLUTION <<<<<<<<<<<<<<
#
def solve():
n, k = input(1)
y = input(1, n)
a = []
b = []
c = []
t = 0
r = 0
for i, j, l in y:
if l and j:
c.append(i)
elif j:
a.append(i)
elif l:
b.append(i)
a.sort(reverse = True)
b.sort(reverse = True)
c.sort(reverse = True)
while r < k:
if not c and not (a and b):
out(-1)
break
u = a[-1] + b[-1] if a and b else 10 ** 10
o = c[-1] if c else 10 ** 10
if u < o:
t += a.pop() + b.pop()
else:
t += c.pop()
r += 1
else:
out(t)
return
#for i in range(input(11)): solve()
solve()
#
# >>>>>>>>>>>>>>>> END OF SOLUTION <<<<<<<<<<<<<<<
#
| 11 | PYTHON3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.