Given a 0-1 string, find a substring as long as possible, which contains 0 equal to the number of 1.

Source: Internet
Author: User

http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1393

The method is fascinating. Also looked at other people's thinking to come out.

First consider turning 0 all into-1. Then a prefix is counted and expressed in sum[i].

Then the substring starting from the starting point is valid as long as the value of Sum[i] equals 0.

If the substring starting point is not 0, then as long as two occurrences of sum[i], the two values must be a valid substring.

For example:

Label: 1 2 3 4 5

Value 0 0 1 1 0

Sum-1-2-1 0-1

I==4 time sum[i]==0, so 1-4 is a valid substring, length 4

sum[1]==sum[3]==sum[5]==-1, so (1,3], (1,5], (3,5) is a valid substring, the maximum value is also 4.

I use a map, in fact, not so troublesome, as long as a variable can replace the sum array, and another marker array can be used instead of map mapping.

1#include <iostream>2#include <string.h>3#include <stdio.h>4#include <map>5 using namespacestd;6 Chars[1000010];7 intt[1000010],sum[1000010];8 intMain ()9 {Ten     //freopen ("A.txt", "R", stdin); Onescanf"%s", s+1); A     intL=strlen (s+1); -      for(intI=1; i<=l;i++) -         if(s[i]=='0') t[i]=-1; the         Elset[i]=1; -     //for (int i=0;i<l;i++) printf ("%d", T[i]); -sum[1]=t[1]; -map<int,int>m; +m[sum[1]]=1; -     intmaxn=0; +      for(intI=2; i<=l;i++) A     { atsum[i]=sum[i-1]+T[i]; -         //printf ("%d\n", Sum[i]); -         if(m[sum[i]]!=0) Maxn=max (maxn,i-M[sum[i]]); -         Elsem[sum[i]]=i; -         if(sum[i]==0) maxn=Max (maxn,i); -     } inprintf"%d\n", MAXN); -     return 0; to}

Given a 0-1 string, find a substring as long as possible, which contains 0 equal to the number of 1.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.