您的位置:首页 > 其它

Codeforces 724B Batch Sort【暴力枚举】

2016-10-09 22:28 337 查看
B. Batch Sort

time limit per test
2 seconds

memory limit per test
256 megabytes

input
standard input

output
standard output

You are given a table consisting of n rows and m columns.

Numbers in each row form a permutation of integers from 1 to m.

You are allowed to pick two elements in one row and swap them, but no more than once for each row. Also, no more than once you are
allowed to pick two columns and swap them. Thus, you are allowed to perform from 0 to n + 1 actions
in total. Operations can be performed in any order.

You have to check whether it's possible to obtain the identity permutation 1, 2, ..., m in each row. In other words, check if one can
perform some of the operation following the given rules and make each row sorted in increasing order.

Input

The first line of the input contains two integers n and m (1 ≤ n, m ≤ 20) —
the number of rows and the number of columns in the given table.

Each of next n lines contains m integers —
elements of the table. It's guaranteed that numbers in each line form a permutation of integers from 1 to m.

Output

If there is a way to obtain the identity permutation in each row by following the given rules, print "YES" (without quotes) in the only line of
the output. Otherwise, print "NO" (without quotes).

Examples

input
2 4
1 3 2 4
1 3 4 2


output
YES


input
4 4
1 2 3 4
2 3 4 1
3 4 1 2
4 1 2 3


output
NO


input
3 6
2 1 3 4 5 6
1 2 4 3 5 6
1 2 3 4 6 5


output
YES


Note

In the first sample, one can act in the following way:

Swap second and third columns. Now the table is
1 2 3 4
1 4 3 2

In the second row, swap the second and the fourth elements. Now the table is
1 2 3 4
1 2 3 4

题目大意:

给你一个N*M的矩阵,你有两种操作:

①从一行中选择两个元素,将其交换。每一行只允许有这样的操作一次。

②选择两列,将两列的元素交换,这种操作只允许有一次。

目标矩阵:使得矩阵每一行都是从1到m的一个递增序列。保证输入的矩阵每一行的数据都是从1-m的。

思路:

1、因为将两列的元素交换这样的操作只有一次,那么我们首先暴力枚举出来两列,使得这两列元素进行交换之后,我们再进行每一行的判断。

2、对应每一行的判断其实也并不难,我们直接暴力判断每一行中的数据有几个a【i】【j】!=j的,如果一个没有,那么其当前行就是一个目标行序列,明显是不需要交换两个元素的,如果有两个,那么明显这两个进行一次交换之后 ,这一行就是从1-m的一个递增的序列了。那么这时候,我们O(N*M)的对当前的矩阵进行判断,如果每一行的需要交换的元素的个数都是0或者2,那么当前情况就是一个可行解,标记输出YES即可。

其中暴力枚举两列交换时间复杂度:O(M*M),其总时间复杂度:O(M*M*N*M)==O(N*M^3),其中N,M最大才20,明显是不会TLE的。

3、注意暴力枚举两列的时候 ,要考虑进去两列相同的情况,就是相当于没有列进行交换的情况。

Ac代码:

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int a[50][50];
int main()
{
int n,m;
while(~scanf("%d%d",&n,&m))
{
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
scanf("%d",&a[i][j]);
}
}
int ok=0;
for(int i=0;i<m;i++)
{
for(int j=0;j<m;j++)
{
int buxing2=0;
for(int k=0;k<n;k++)
{
swap(a[k][i],a[k][j]);
}
for(int ii=0;ii<n;ii++)
{
int flag=0;
for(int jj=0;jj<m;jj++)
{
if(a[ii][jj]!=jj+1)flag++;
}
if(flag==0||flag==2)continue;
else buxing2=1;
}
for(int k=0;k<n;k++)
{
swap(a[k][i],a[k][j]);
}
if(buxing2==1)continue;
else ok=1;
}
}
if(ok==1)printf("YES\n");
else printf("NO\n");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Codeforces 724B