#include using namespace std; typedef signed long long ll; #undef _P #define _P(...) (void)printf(__VA_ARGS__) #define FOR(x,to) for(x=0;x<(to);x++) #define FORR(x,arr) for(auto& x:arr) #define ITR(x,c) for(__typeof(c.begin()) x=c.begin();x!=c.end();x++) #define ALL(a) (a.begin()),(a.end()) #define ZERO(a) memset(a,0,sizeof(a)) #define MINUS(a) memset(a,0xff,sizeof(a)) //------------------------------------------------------- int N,M; int X[505050]; int miy[505050],may[505050]; int L[7070707]; int R[7070707]; int add[7]={0,1,1,2,3,3,0}; int lef[7]={0,0,1,1,1,1,0}; int rig[7]={0,1,0,1,1,1,0}; // before, ->, <- , <-> , -><-->, <-->-<, done // 1-non 2-start 3-end int mat[7][7]={ {1,2,3,1,2,3,1}, {0,1,0,3,1,0,3}, {0,0,1,2,0,1,2}, {0,2,3,1,0,0,1}, {0,1,0,0,1,0,3}, {0,0,1,0,0,1,2}, {0,0,0,0,0,0,1}, }; int from[7][2][2]; int to[7][2][2]; void solve() { int i,j,k,l,r,x,y; string s; cin>>N>>M; int miX=N,maX=0; FOR(i,M) { cin>>X[i]>>x; miy[i]=may[i]=X[i]; while(x--) { cin>>y; miy[i]=min(miy[i],y); may[i]=max(may[i],y); } L[miy[i]]++; L[X[i]]--; R[X[i]]++; R[may[i]]--; miX=min(miX,miy[i]); maX=max(maX,may[i]); } FOR(i,7) FOR(x,2) FOR(y,2) from[i][x][y]=1<<30; from[0][0][0]=0; FOR(i,N) { FOR(j,7) FOR(x,2) FOR(y,2) to[j][x][y]=1<<30; FOR(x,7) FOR(y,7) { if(mat[x][y]==0) continue; if(L[i]&&lef[y]==0) continue; if(R[i]&&rig[y]==0) continue; FOR(j,2) FOR(k,2) { if(from[x][j][k]>=1<<30) continue; int j2=j+(mat[x][y]==2); int k2=k+(mat[x][y]==3); if(j2==2 || k2==2) continue; to[y][j2][k2]=min(to[y][j2][k2],from[x][j][k]+add[y]); } } L[i+1]+=L[i]; R[i+1]+=R[i]; swap(from,to); } cout<