codeforces 754 A Lesha and array splitting
題目描述:
One spring day on his way to university Lesha found an array A. Lesha likes to split arrays into several parts. This time Lesha decided to split the array A into several, possibly one, new arrays so that the sum of elements in each of the new arrays is not zero. One more condition is that if we place the new arrays one after another they will form the old array A
Lesha is tired now so he asked you to split the array. Help Lesha!
Input
The first line contains single integer n (1 ≤ n ≤ 100) — the number of elements in the array A.
The next line contains n integers a1, a2, ..., an ( - 103 ≤ ai ≤ 103) — the elements of the array A.
Output
If it is not possible to split the array A
Otherwise in the first line print "YES" (without quotes). In the next line print single integer k — the number of new arrays. In each of the next k lines print two integers li and ri which denote the subarray A
- l1 = 1
- rk = n
- ri + 1 = li + 1 for each 1 ≤ i < k.
If there are multiple answers, print any of them.
Example
Input
3
1 2 -3
Output
YES
2
1 2
3 3
Input
8
9 -12 3 4 -4 -10 7 3
Output
YES
2
1 2
3 8
Input
1
0
Output
NO
Input
4
1 2 3 -5
Output
YES
4
1 1
2 2
3 3
4 4
題目大意:
將一串陣列分成相連的任意份,問是否有一種分法將其分成每一份的和都不為0
題目分析:
顯而易見只有全0的時候不存在分法,其他的肯定都存在。現在我們來看,如果這個串首位不為0,那麼我們將其作為開頭,看他的下一位是否是0,如果是0,則一直包含,直到遇到下一個不為0的數;如果這個串的首位是0,那麼我們要看這個0的位置是不是總串的首位,如果是,那麼找到後面第一個不為0的數作為這個字串的末尾,如果這個0不是總串的首位,則將其包含到前一個字串的末尾(以 0 0 1 0 0這個例子做理解)
AC程式碼:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
const int maxn=105;
struct node
{
int l,r;
}p[maxn];
int x[maxn];
int t;
int main()
{
while(~scanf("%d",&t))
{
memset(p,0,sizeof(p));
memset(x,0,sizeof(x));
bool sign=false;
for(int i=1;i<=t;i++)
{
scanf("%d",&x[i]);
if(x[i]!=0)
sign=true;
}
if(!sign)
cout<<"NO"<<endl;
else
{
int k=1;
for(int i=1;i<=t;i++)
{
p[k].l=i;
if(x[i]!=0)
{
while(x[i+1]==0&&i<t)
{
i++;
}
p[k++].r=i;
}
else
{
if(i==1)
{
while(i<t)
{
i++;
if(x[i]!=0)
{
p[k++].r=i;
break;
}
}
}
else
{
p[k-1].r++;
}
}
}
cout<<"YES"<<endl;
cout<<k-1<<endl;
for(int i=1;i<k;i++)
cout<<p[i].l<<" "<<p[i].r<<endl;
}
}
return 0;
}