Andrewid the Android is a galaxy-famous detective. He is now investigating the case of vandalism at the exhibition of contemporary art.
The main exhibit is a construction of n matryoshka dolls that can be nested one into another. The matryoshka dolls are numbered from1 to n. A matryoshka with a smaller number can be nested in a matryoshka with a higher number, two matryoshkas can not be directly nested in the same doll, but there may be chain nestings, for example, 1 → 2 → 4 → 5.
In one second, you can perform one of the two following operations:
- Having a matryoshka a that isn't nested in any other matryoshka and a matryoshkab, such that b doesn't contain any other matryoshka and is not nested in any other matryoshka, you may puta in b;
- Having a matryoshka a directly contained in matryoshkab, such that b is not nested in any other matryoshka, you may geta out of b.
According to the modern aesthetic norms the matryoshka dolls on display were assembled in a specific configuration, i.e. as several separate chains of nested matryoshkas, but the criminal, following the mysterious plan, took out all the dolls and assembled them into a single large chain (1 → 2 → ... → n). In order to continue the investigation Andrewid needs to know in what minimum time it is possible to perform this action.
The first line contains integers n (1 ≤ n ≤ 105) andk (1 ≤ k ≤ 105) — the number of matryoshkas and matryoshka chains in the initial configuration.
The next k lines contain the descriptions of the chains: thei-th line first contains number mi (1 ≤ mi ≤ n), and thenmi numbersai1, ai2, ..., aimi — the numbers of matryoshkas in the chain (matryoshka ai1 is nested into matryoshkaai2, that is nested into matryoshkaai3, and so on till the matryoshkaaimi that isn't nested into any other matryoshka).
It is guaranteed that m1 + m2 + ... + mk = n, the numbers of matryoshkas in all the chains are distinct, in each chain the numbers of matryoshkas follow in the ascending order.
In the single line print the minimum number of seconds needed to assemble one large chain from the initial configuration.
3 2 2 1 2 1 3
1
7 3 3 1 3 7 2 2 5 2 4 6
10
In the first sample test there are two chains: 1 → 2 and3. In one second you can nest the first chain into the second one and get1 → 2 → 3.
In the second sample test you need to disassemble all the three chains into individual matryoshkas in 2 + 1 + 1 = 4 seconds and then assemble one big chain in 6 seconds.
题目大意:有n个套娃,大的能套在小的上面,先已有m个链,最终需按顺序套好,每次可取下一个最上面的或把一个单独的套在一整个链上。求最小步数
思路:除和1相连的有序链外,剩下的每个链上面的都要取下一次再套上一次,最下面的需要套一次。只需找出1,2,3……已排好的有几个就行了
#include<iostream>
#include<cstdio>
#define manx 100005
using namespace std;
int main()
{
int n,k,f,cot=1,m,x,ans=0;
scanf("%d%d",&n,&k);
for (int i=0; i<k; i++){
scanf("%d%d",&m,&f);
if(f==1){
for (int i=2; i<=m; i++){
scanf("%d",&x);
if(x==i) cot++;
}
ans+=m-cot;
}
else{
for (int i=1; i<m; i++)
scanf("%d",&x);
ans+=m-1;
}
}
ans+=n-cot;
printf("%d\n",ans);
return 0;
}