CF376D
题解
- 因为n组数据是要按字典序排列。所以我们只需考虑上下相邻的两组是否满足条件,总共有n-1对。
- 每一对都有一个变化的区间,最后我们求出n-1对的变化区间。变化区间自己写写就能找到规律。最后判断是否存在一个区间,使所有的对都在里面。
- 我们可以根据括号匹配的思想,相当于差分的思想。如果[x1,y1]满足条件,那么c[x1]++,c[y1+1]--。最后我们求前缀和为n-1那么就满足条件。
- 具体的细节见代码。
代码
#include <bits/stdc++.h>
using namespace std;
int const N = 1e6 + 10;
int n,c,d[N];
vector<int>a[N];
void updata(int l,int r){
d[l]++;
d[r+1]--;
}
int main(){
scanf("%d%d",&n,&c);
for(int i=1;i<=n;i++){
int tmp;
scanf("%d",&tmp);
a[i].push_back(tmp);
for(int j=1;j<=a[i][0];j++){
scanf("%d",&tmp);
a[i].push_back(tmp);
}
}
for(int i=1;i<n;i++){
int len = min(a[i][0],a[i+1][0]);
int x,y,j;
for(j=1;j<=len;j++){
x = a[i][j];
y = a[i+1][j];
if(x != y) break;
}
if(j > len && a[i][0] > a[i+1][0]){
printf("-1\n");
return 0;
}
if(x != y){
if(x < y){
updata(0,c-y);
updata(c-x+1,c-1);
}else{
updata(c-x+1,c-y);
}
}else updata(0,c-1);
}
int sum = 0;
for(int i=0;i<=c-1;i++){
sum += d[i];
if(sum == n-1){
printf("%d\n",i);
return 0;
}
}
printf("-1\n");
return 0;
}