菜鸟学习ACM,纪录自己成长过程中的点滴。
学习的路上,与君共勉。
ACM学习-POJ-1063-Flip and Shift
Flip and Shift
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 6623 | Accepted: 3086 |
Description
This puzzle consists of a random sequence of m black disks and n white disks on an oval-shaped track, with a turnstile capable of flipping (i.e., reversing) three consecutive disks. In Figure 1, there are 8 black disks and 10 white disks on the track. You may spin the turnstile to flip the three disks in it or shift one position clockwise for each of the disks on the track (Figure 1).
The goal of this puzzle is to gather the disks of the same color in adjacent positions using flips and shifts. (Figure 2)
You are to write a program which decides whether a given sequence can reach a goal or not. If a goal is reachable, then write a message "YES"; otherwise, write a message "NO".
Input
The input consists of T test cases. The number of test cases ) (T is given in the first line of the input file. Each of the next T lines gives a test case. A test case consists of an integer, representing the sum of m and n, and a sequence of m+n 0s and 1s, representing an initial sequence. A 0 denotes a white disk and a 1 denotes a black disk. The sum of m and n is at least 10 and does not exceed 30. There is a space between numbers.
Output
The output should print either "YES" or "NO" for each test case, one per line.
Sample Input
2 18 0 0 1 0 1 1 1 1 0 1 0 0 1 0 0 0 0 1 14 1 1 0 0 1 1 1 0 0 1 1 0 1 0
Sample Output
YES NO
Source
题目要求:
有一些珠子排成一圈,珠子有两种颜色:黑和白。每次操作可以调换中间隔着一个珠子的两珠子的位置,给出这个圈子的初始状态,问最终能否通过操作让圈子中所有同色的珠子排在一起,即黑白分开。
题目分析:
题目分析:
分两种情况,珠子总数为偶数,那么奇数位置上的珠子无法移动到偶数位上,偶数位的也无法移动到奇数位上,但在奇数位内部和偶数位内部可以自由移动。任何一个连续区间内奇数位和偶数位的数量差都不超过1。因此想要黑色珠子全都连在一起,则要求奇数位上的黑色珠子数量和偶数位上的黑色珠子数量之差的绝对值要小于等于1。
对于第二种情况,珠子总数为奇数,这种情况一定可以达到目标,因为如果任意相邻两珠子可交换则一定可以达到目标。对于总数为奇数的情况,相当于将一种相邻两珠子可交换的排列方式更改了珠子的排列顺序,但交换方式不变。例如,7个珠子,1357246。把这个序列首尾相接则形成了一个相邻两两可交换的环,可以达到任何目标状态。
对于第二种情况,珠子总数为奇数,这种情况一定可以达到目标,因为如果任意相邻两珠子可交换则一定可以达到目标。对于总数为奇数的情况,相当于将一种相邻两珠子可交换的排列方式更改了珠子的排列顺序,但交换方式不变。例如,7个珠子,1357246。把这个序列首尾相接则形成了一个相邻两两可交换的环,可以达到任何目标状态。
下面给出AC代码:
#include <stdio.h>
#include <math.h>
#define MAX_NUM 31
int main()
{
int n;
int i;
int arr_[MAX_NUM];
int num_;
int count_odd;
int count_even;
scanf("%d",&n);
while (n--)
{
scanf("%d", &num_);
for (i=0; i<num_; i++)
{
scanf("%d", &arr_[i]);
}
if (num_ % 2 == 1)
{
printf("YES\n");
}
else
{
count_even = 0;
count_odd = 0;
for (i=0; i<num_; i++)
{
if (arr_[i] == 1)
{
if (i % 2)
{
count_odd++;
}
else
count_even++;
}
}
if ( abs(count_even - count_odd) <= 1 )
{
printf("YES\n");
}
else
{
printf("NO\n");
}
}
}
return 0;
}