Bob has a permutation of integers from 1 to n. Denote this permutation as p. The i-th element of p will be denoted as pi. For all pairs of distinct integers i, j between 1 and n, he wrote the number ai, j = min(pi, pj). He writes ai, i = 0 for all integer i from 1 to n.
Bob gave you all the values of ai, j that he wrote down. Your job is to reconstruct any permutation that could have generated these values. The input will be formed so that it is guaranteed that there is at least one solution that is consistent with the information given.
The first line of the input will contain a single integer n (2 ≤ n ≤ 50).
The next n lines will contain the values of ai, j. The j-th number on the i-th line will represent ai, j. The i-th number on the i-th line will be 0. It's guaranteed that ai, j = aj, i and there is at least one solution consistent with the information given.
Print n space separated integers, which represents a permutation that could have generated these values. If there are multiple possible solutions, print any of them.
2 0 1 1 0
2 1
5 0 2 2 1 2 2 0 4 1 3 2 4 0 1 3 1 1 1 0 1 2 3 3 1 0
2 5 4 1 3
In the first case, the answer can be {1, 2} or {2, 1}.
In the second case, another possible answer is {2, 4, 5, 1, 3}.
解题思路:
按列说这一列中最大的数代表着这一位中会出现的最小值,保存可能的值深搜就可以,因为会有多组解输出一个就行。
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
bool vis[100];
int ans[100];
struct node
{
int cc[100];
int jj;
}num[100];
void wc(int ii,int xx,int n)
{
int i,j;
num[ii].jj=0;
for(i=xx;i<=n;i++)
{
num[ii].cc[num[ii].jj++]=i;
}
}
int nn;
void DFS(int x,int n)
{
if(nn==n)
{
return ;
}
int i,j;
for(i=0;i<num[x].jj;i++)
{
if(!vis[num[x].cc[i]])
{
ans[nn++]=num[x].cc[i];
vis[num[x].cc[i]]=true;
DFS(x+1,n);
if(nn==n)
return ;
vis[num[x].cc[i]]=false;
nn--;
}
if(nn==n)
return;
}
}
int main()
{
int n;
scanf("%d",&n);
int i,j;
for(i=1;i<=n;i++)
{
int mm=-1;
for(j=0;j<n;j++)
{
int xx;
scanf("%d",&xx);
mm=max(mm,xx);
}
wc(i,mm,n);
}
nn=0;
memset(vis,false,sizeof(vis));
DFS(1,n);
for(i=0;i<n;i++)
{
if(i==0)
printf("%d",ans[i]);
else
printf(" %d",ans[i]);
}
printf("\n");
return 0;
}