Square Problem

本文探讨了一种算法,旨在判断给定长度的棍子是否能组成正方形。通过分配棍子到正方形的四条边并计算每条边的总长度来实现。核心在于检查所有棍子分配后的边长是否相等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Problem Description: Given a set of sticks of various lengths, is it possible to join them end-to-end to form a square? 

Input:

4 1 1 1 1

5 10 20 30 40 50

8 1 7 2 6 4 4 3 5

Output

Yes

No

Yes

Problem Analysis:

This problem is the assignment of the i-th stick to corresponding edges. Since there are 4 edges in the square, therefore, we can assign the stick to each edge of the square. When all sticks are judged, we will compute the length of each edge. Based on such thought, corresponding implement

#include <stdio.h>
#include<string.h>
long long a[1005];
long long b[1005];
int n;
int sum;
int flag=0;
void Init(){
	int i;
	scanf("%d",&n);
    for(i=0;i<n;i++){
        scanf("%lld",&a[i]);
        sum+=a[i];
    }
}
void traceback(int t){
    int i;
    if(flag)
    	return ;
    if(t==n){
        for(i=1;i<4;i++)
            if(b[i]!=sum)
       		 	return;
        flag=1;
        printf("yes");
        return ;
    }
 
    for(i=0;i<4;i++){
        b[i]+=a[t];
        if(b[i]<=sum)
            traceback(t+1);
        b[i]-=a[t];
    }
}
 
int main()
{
    int i;
    sum=0;
   	Init(); 
    if(sum%4){
        printf("no");
        return 0;
    } 
    sum=sum/4;
    memset(b,0,sizeof(b));
    traceback(0);
   if(!flag)
        printf("no");
    return 0;
}

is tabulated as follows

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值