#include <bits/stdc++.h>
#define startt ios_base::sync_with_stdio(false);cin.tie(0);
typedef long long ll;
using namespace std;
#define vint vector<int>
#define all(v) v.begin(), v.end()
#define MOD 1000000007 //1e9+7
#define MOD2 998244353
#define MX 1000000000 //1e9
#define MXL 1000000000000000000
#define PI (ld)2*acos(0.0)
#define pb push_back
#define sc second
#define fr first
#define inte long long
#define ld long doublelu
int main()
{
// 1 1
// 3 -1 -2 -3
startt
ll x,k;
cin>>x>>k;
vector<pair<ll,ll>> b;
while(k--){
int y;
cin>>y;
int d=1;
ll j=0,m=0;
vector<ll> v;
// cout<<"yes"<<" ";
for(int i=0;i<y;i++){
ll a;
cin>>a;
if(a>=0 and d)x+=a;
else{
d=0;
j+=a;
v.pb(j);
// cout<<j<<" ";
}
}
int n=v.size();
if(n>1){
vector<pair<ll,ll>> c;
for(int i=0;i<n;i++){
m=min(m,v[i]);
if(v[i]>0){
c.pb({m,v[i]});
// cout<<m<<" "<<v[i]<<" ";
}
}
n=c.size();
if(n>0){
sort(c.rbegin(), c.rend());
b.pb({c[0].first,c[0].second});
ll st=c[0].second;
for(int i=0;i<n;i++){
if(c[i].second>st){
b.pb({c[i].first,c[i].second-st});
st=c[i].second;
// cout<<c[i].first<<" "<<c[i].second<<" ";
}
}
}
}
}
sort(b.rbegin(), b.rend());
for(auto it: b){
if(abs(it.first)<=x){
x+=it.second;
}
else break;
}
cout<<x<<endl;
return 0;
}
1523B - Lord of the Values | 1406C - Link Cut Centroids |
2409. Count Days Spent Together | 2410. Maximum Matching of Players With Trainers |
1604C - Di-visible Confusion | 997A - Convert to Ones |
218A - Mountain Scenery | 486B - OR in Matrix |
1405A - Permutation Forgery | 1733A - Consecutive Sum |
1733B - Rule of League | 1733C - Parity Shuffle Sorting |
1264A - Beautiful Regional Contest | 1695A - Subrectangle Guess |
467B - Fedor and New Game | 252C - Points on Line |
735C - Tennis Championship | 992A - Nastya and an Array |
554A - Kyoya and Photobooks | 79B - Colorful Field |
265B - Roadside Trees (Simplified Edition) | 1362C - Johnny and Another Rating Drop |
1214C - Bad Sequence | 1091B - New Year and the Treasure Geolocation |
244A - Dividing Orange | 1061C - Multiplicity |
1312A - Two Regular Polygons | 801A - Vicious Keyboard |
510B - Fox And Two Dots | 616D - Longest k-Good Segment |