Monday, August 6, 2018

Codeforces 96A Football Solution in C (Counting Consecutive Runs)

Football (96A) is about finding a long run of identical characters in a string. Tracking the length of the current run is a pattern you will reuse in many problems, from compressing strings to finding the longest streak in an array.

The problem in short

A string of 0s and 1s (length up to 100) describes where the players stand on a field: 0 for one team and 1 for the other. The situation is dangerous if at least 7 players of the same team stand next to each other. Print YES if it is dangerous, otherwise NO.

Full statement: Codeforces 96A – Football.

Approach: track the current run

Walk through the string from left to right while keeping a counter run, which is the length of the block of equal characters ending at the current position.

  • Start with run = 1 for the first character.
  • If the current character equals the previous one, increase run. If run reaches 7, we can stop and print YES.
  • Otherwise a new block starts, so reset run to 1.

If we reach the end without the counter hitting 7, print NO.

Examples

001001

The longest blocks are “00”, so run never passes 2 → NO.

1000000001

After the first 1, the 0s build up a run of 8, which hits 7 along the way → YES.

Solution in C

#include <stdio.h>

int main(void) {
    char s[105];
    scanf("%s", s);

    int run = 1;
    for (int i = 1; s[i] != '\0'; i++) {
        if (s[i] == s[i - 1]) {
            run++;
            if (run >= 7) {
                printf("YES\n");
                return 0;
            }
        } else {
            run = 1;
        }
    }

    printf("NO\n");
    return 0;
}

An even shorter alternative

Since the condition is “7 equal characters in a row”, you could also check whether the string contains "0000000" or "1111111" using strstr. That is a perfectly good solution here. The run counter is still worth knowing because it generalizes: it works for any threshold, any alphabet and any array, without building a search pattern.

Complexity

One pass: O(n) time and O(1) extra memory.

Common mistakes

  • Starting run at 0 instead of 1, which makes every run look one shorter.
  • Checking for exactly 7 (run == 7 only at the end of a block) and missing longer runs. Checking as soon as run reaches 7 avoids this.

Practice next

266A Stones on the Table uses the same “compare with the previous character” idea.

4 comments:

  1. Why we use o-6 ???

    ReplyDelete
    Replies
    1. It doesn't matter.you can used for(i=0;i<o;i++) in this statement.

      Delete
  2. #include
    int main()
    {

    int i,c=1;
    char f[100];
    gets(f);
    for(i=0;i<strlen(f);i++){
    if(f[i] == f[i+1]){
    c++;
    if(c==7){
    printf("YES");
    return 0;
    }
    }
    else{c=1;}
    }
    printf("NO\n");


    return 0;

    }

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete