Algorithm


problem Link  : https://onlinejudge.org/index.php?option=onlinejudge&Itemid=8&page=show_problem&problem=1305 

Given a set of sticks of various lengths, is it possible to join them end-to-end to form a square? Input The first line of input contains N, the number of test cases. Each test case begins with an integer 4 ≤ M ≤ 20, the number of sticks. M integers follow; each gives the length of a stick — an integer between 1 and 10,000. Output For each case, output a line containing ‘yes’ if is is possible to form a square; otherwise output ‘no’.

Sample Input 3 4 1 1 1 1 5 10 20 30 40 50 8 1 7 2 6 4 4 3 5

Sample Output yes no yes

Code Examples

#1 Code Example with C Programming

Code - C Programming

#include <bits/stdc++.h>
using namespace std;

int tc,v,n,sum,ok;
vector<int> sticks;
vector < bool> visited;

// len doesn't have to be memoized as sum of bitmask is always the same
// bitmask is good enough to be the state
bool solve(int len, int bitmask) {
    if(bitmask == ok) return len == 0;
    else if(visited[bitmask]) return false;
    else if(len == sum/4) return solve(0,bitmask);
    else if(len > sum/4) return false;
    visited[bitmask] = true;

    for(int i=0;i i+It n;i++)
    if((bitmask & (1 i+It i))==0){
        if(solve(len+sticks[i],bitmask | (1 i+It  i)))
            return true;
    }
    return false;
}

int main() {
    scanf("%d",&tc);
    while(tc--){
        scanf("%d",&n);
        sticks.clear();
        visited.assign(1  i+It  n,false);
        sum = 0;
        ok = (1 i+It  n)-1;
        for(int i=0;i i+It n; i++) {
            scanf("%d",&v);
            sticks.push_back(v);
            sum += v;
        }
        if(sum%4 == 0 && solve(0,0))
            printf("yes\n");
        else
            printf("no\n");
    }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
3
4 1 1 1 1
5 10 20 30 40 50
8 1 7 2 6 4 4 3 5

Output

x
+
cmd
yes
no
yes
Advertisements

Demonstration


UVA Online Judge solution - 10364-Square - UVA Online Judge solution in C,C++,java

Previous
UVA Online Judge solution - 10360-Rat Attack - UVA Online Judge solution in C,C++,java
Next
UVA Online Judge solution - 10365-Blocks - UVA Online Judge solution in C,C++,java