CF274D Lovely Matrix 题解
teylnol_evteyl · · 题解
对于矩阵的每一行,可以确定一些列之间的关系,也就是对于
考虑优化。可以发现只需要从比它小的最大的点向它连边,但是如果这样的点有多个就必须每个点向它连边。考虑对每行对每个数值建立虚拟节点,每个值不是
#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 5;
int n, m, a[N], x[N], s, pid;
int la[N], ne[N], en[N], idx, du[N];
int q[N], hh, tt, path[N];
void add(int a, int b)
{
ne[ ++ idx] = la[a];
la[a] = idx;
en[idx] = b;
du[b] ++ ;
}
bool topo()
{
int cnt = 0;
hh = 0, tt = -1;
for(int i = 1; i <= pid; i ++ )
if(!du[i])
q[ ++ tt] = i;
while(hh <= tt)
{
int u = q[hh ++ ];
path[ ++ cnt] = u;
for(int i = la[u]; i; i = ne[i])
{
int v = en[i];
du[v] -- ;
if(!du[v]) q[ ++ tt] = v;
}
}
return cnt == pid;
}
int main()
{
scanf("%d%d", &n, &m);
pid = m;
for(int i = 1; i <= n; i ++ )
{
s = 0;
for(int j = 1; j <= m; j ++ )
{
scanf("%d", &a[j]);
if(a[j] != -1) x[ ++ s] = a[j];
}
sort(x + 1, x + s + 1);
s = unique(x + 1, x + s + 1) - x - 1;
for(int j = 1; j <= m; j ++ )
if(a[j] != -1)
{
int t = lower_bound(x + 1, x + s + 1, a[j]) - x;
if(t > 1) add(pid + t - 1, j);
add(j, pid + t);
}
pid += s;
}
if(topo())
{
for(int i = 1; i <= pid; i ++ )
if(path[i] <= m)
printf("%d ", path[i]);
}
else puts("-1");
return 0;
}