A straight is a poker hand containing five cards of sequential rank, not necessarily to be the same suit. For example, a hand containing 7 club, 6 spade, 5 spade, 4 heart and 3 diamond forms a straight. In this problem, we extend the definition of a straight to allow 3 to 5 cards of sequential rank. Hence a hand containing K spade, Q club, and J heart is also a straight.
Mr. Panda is playing a poker game called Straight Master. The game uses a large deck of card that has N ranks from 1 to N. The rule of the game is simple: split the cards in Mr. Panda's hand into several straights of length from 3 to 5.
Now given a hand of cards, can you help Mr. Panda to determine if it is possible to split the cards into straights?
Input
The first line of the input gives the number of test cases, T. T test cases follow.
Each test case contains two lines. The first line contains an integer N, indicating the number of ranks in the deck. The next line contains N integers a1, a2, ..., aN indicating the number of cards for each rank in Mr. Panda's hand.
- 1 ≤ T ≤ 100.
- 1 ≤ N ≤ 2 × 105.
- 0 ≤ ai ≤ 109.
- .
Output
For each test case, output one line containing "Case #x: y", where x is the test case number (starting from 1) and y is Yes if Mr. Panda can split all his cards into straights of length from 3 to 5, or No otherwise.
Example
Input
2 13 1 2 2 1 0 0 0 0 0 0 0 0 0 13 1 1 1 1 0 1 1 0 0 0 0 0 0
Output
Case #1: Yes Case #2: No
Note
In the first test case, Mr. Panda can split his cards into two straights: [1, 2, 3] and [2, 3, 4]. In the second test case, there is no way to form a straight for card 6 and 7.
题意:
有n种扑克牌,每种扑克牌有ai张,每次可以打出3到5张连续的牌作为顺子,问这副牌能不能用顺子全打出来。
差分:
差分就是将一串数分别于前一个数做差,例如:
一个序列1 2 5 4 7 3,差分后得到1 1 3 -1 3 -4 -3
这里注意得到的差分序列第一个数和原来的第一个数一样(相当于第一个数减0)
差分序列最后比原序列多一个数(相当于0减最后一个数)
性质:
1、差分序列求前缀和可得原序列
2、将原序列区间[L,R]中的元素全部+1,可以转化操作为差分序列L处+1,R+1处-1
3、按照性质2得到,每次修改原序列一个区间+1,那么每次差分序列修改处增加的和减少的相同
思路:
换一个思路,给定一个长度为0的序列,每次可以选择长度为3,4,5的区间并将这个区间内的数全部加一,最终可以得到一个新的序列,问这个序列的每个数分别是多少,这个序列就是给定的n种扑克牌。
对于这个问题,可以用差分的思想,对于区间[L, R],可以开一个新的数组b,这个区间加一后可以认为是b[L]+=1, b[R+1]-=1, b的前缀和即为对应的数字。
原来那个问题就可以转化为给你一个序列,问这个序列可不可以由上面的操作得到。也可以构建一个差分数组b,其中b[i] = a[i]-a[i-1]。如果这个b数组对于每个相邻距离大于等于3的b[i] 和 b[j] (j>=i+3),如果每一对的和加起来等于0,则给定的数列是可以得到的,否则就无法得到。
代码:
#include <cstdio>
using namespace std;
const int MAXN = 200005;
int a[MAXN],b[MAXN];
int main(){
int T,N;
scanf("%d",&T);
for(int _=1 ; _<=T ; ++_){
scanf("%d",&N);
for(int i=1 ; i<=N ; ++i)scanf("%d",&a[i]);
a[N+1] = 0;
for(int i=1 ; i<=N+1 ; ++i)b[i] = a[i] - a[i-1];
bool flag = true;
if(b[1]<0 || b[2]<0 || b[3]<0)flag = false;
else {
long long sum = 0;
for(int i=1 ; i<=N+1 ; ++i){
if(b[i] > 0)sum += b[i];
int t = i + 3;
if(t > N+1)break;
if(b[t] < 0){
sum += b[t];
b[t] = 0;
}
if(sum < 0)break;
}
if(sum != 0)flag = false;
}
if(flag)printf("Case #%d: Yes\n",_);
else printf("Case #%d: No\n",_);
}
return 0;
}