Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 5677 | Accepted: 2213 |
Description
Consider a binary string (b1…bN) with N binary digits. Given such a string, the matrix of Figure 1 is formed from the rotated versions of the string.
b1 | b2 | … | bN−1 | bN |
b2 | b3 | … | bN | b1 |
… | ||||
bN−1 | bN | … | bN−3 | bN−2 |
bN | b1 | … | bN−2 | bN−1 |
Figure 1. The rotated matrix
Then rows of the matrix are sorted in alphabetical order, where ‘0’ is before ‘1’. You are to write a program which, given the last column of the sorted matrix, finds the first row of the sorted matrix.
As an example, consider the string (00110). The sorted matrix is
0 | 0 | 0 | 1 | 1 |
0 | 0 | 1 | 1 | 0 |
0 | 1 | 1 | 0 | 0 |
1 | 0 | 0 | 0 | 1 |
1 | 1 | 0 | 0 | 0 |
and the corresponding last column is (1 0 0 1 0). Given this last column your program should determine the first row, which is (0 0 0 1 1).
Input
The first line contains one integer N ≤ 3000, the number of binary digits in the binary string. The second line contains N integers, the binary digits in the last column from top to bottom.
Output
The first line contains N integers: the binary digits in the first row from left to right.
Sample Input
5
1 0 0 1 0
Sample Output
0 0 0 1 1
Source
题目链接:http://poj.org/problem?id=1147
题目大意:一个长度为n的二进制序列循环左移n-1次得到n个不同的序列,对这n个序列按字典序排序得到一个矩阵,给出这个矩阵的最后一列,输出其第一行
题目分析:题解PDF,很详细
#include <cstdio>
#include <cstring>
using namespace std;
int const MAX = 3005;
int a[MAX], tmp[MAX],next[MAX];
bool used[MAX];
int main()
{
int n, cnt = 0;
scanf("%d", &n);
memset(used, false, sizeof(used));
memset(tmp, 0, sizeof(tmp));
for(int i = 0; i < n; i++)
{
scanf("%d", &a[i]);
if(a[i])
cnt++;
}
for(int i = n - cnt; i < n; i++)
tmp[i] = 1;
for(int i = 0; i < n; i++)
{
int j = 0;
while(tmp[i] != a[j] || used[j])
j++;
used[j] = true;
next[i] = j;
}
int ind = 0;
for(int i = 0; i < n; i++)
{
ind = next[ind];
if(i != (n - 1))
printf("%d ", a[ind]);
else
printf("%d\n", a[ind]);
}
}