J. Straight Master
time limit per test
2.0 s
memory limit per test
256 MB
input
standard input
output
standard output
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 5cards 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
Copy
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
Copy
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.
题意:
给你一副牌,问是否能全部组成长度为3~5的shun顺子。
思路:
首先考虑长度为3~5可以转化为大于等于3,因为大于5的顺子可以拆成若干3~5的顺子。
然后我们可以对一个全空的数组,每次取一个大于3的区间,区间内元素全部+1.看能否组成a数组。
可以用一个数组dis记录a[i]-a[i-1]。如果dis>0,那么是一个区间的起始位置;dis<0是结束位置。直接扫一遍,用sum记录dis[i]与dis[i+3]的和。如果sum=0,那么就可以构成。每次加过结束位置,将位置变为0,如果dis[i]<0 || sum<0,则不合法。
代码:
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define MAXN 200005
#define mod 1000000007
int n,dis[MAXN],a[MAXN];
int main()
{
int t;
scanf("%d",&t);
for(int tt=1;tt<=t;tt++)
{
scanf("%d",&n);
memset(a,0,sizeof a);
for(int i=1;i<=n;i++)
scanf("%d",a+i);
memset(dis,0,sizeof dis);
for(int i=1;i<=n+1;i++)
dis[i]=a[i]-a[i-1];
int sum=0;
for(int i=1;i<=n-2;i++)
{
if(dis[i]>0) sum+=dis[i];
if(dis[i]<0)
{
sum=1;
break;
}
if(dis[i+3]<0)
{
sum+=dis[i+3];
dis[i+3]=0;
}
if(sum<0) break;
}
//if(dis[2]<0 || dis[3]<0) sum=1;
printf("Case #%d: %s\n",tt,sum==0? "Yes":"No");
}
return 0;
}