题意:给你一组排列P的数和一个二阶矩阵A,当且仅当矩阵A的元素为1时,数列P所对应的行和列的数字可以交换。你的任务就是通过这种方式,使数列P中较小的元素尽量靠前。
解题思路:刚开始看这道题时以为简简单单的把可以调换的两个数比较一下,小的在前就行了。但这只是想想,还是没理解题意,事实上没那么简单。。(在此之前要加上个Floyd三层循环,把所有可以调换的数(包括直接,间接)都先找出来,然后再比较可以调换的数就行了。。)
代码:
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
char map[310][310];
int main(){
int n;int a[310];
scanf("%d",&n);
for(int i=0;i<n;i++){
scanf("%d",&a[i]);
}
for(int i=0;i<n;i++){
scanf("%s",map[i]);//老套路,按字符串输入
}
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
for(int k=0;k<n;k++){
if(map[j][i]=='1'&&map[i][k]=='1'){
map[j][k]='1';//把间接的可以调换的转换成直接的
}
}
}
}
// for(int i=0;i<n;i++){
// printf("%s\n",map[i]);
// }
for(int i=0;i<n;i++){
for(int j=i+1;j<n;j++){
if(map[i][j]=='1'&&a[i]>a[j]){//直接判断就行啦!
swap(a[i],a[j]);
}
}
}
for(int i=0;i<n;i++){
printf("%d ",a[i]);
}
return 0;
}