Square
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 12859 Accepted Submission(s): 4078
#include<stdio.h>
#include<string.h>
int flag;
int m,a[30],sum ,vis[30];
void bfs(int s,int l,int k){
if(s==5)
{
flag=1;
return;
}
if(l==sum)
{
bfs(s+1,0,0);
if(flag)
return;
}
for(int j=k;j<m;j++){
if(!vis[j]&&l+a[j]<=sum)
{
int temp=a[j];
vis[j]=1;
bfs(s,l+temp,j+1);
vis[j]=0;
if(flag)
return;
}
}
}
int main()
{int n;
scanf("%d",&n);
while(n--){
scanf("%d",&m);
sum=0;
for(int i=0;i<m;i++)
{
scanf("%d",&a[i]);
sum+=a[i];
}
if(sum%4==1){
printf("no\n");
continue;
}
int i;
for(i=0;i<m;i++){
if(a[i]>sum/4)
break;
}
if(i!=m){
printf("no\n");
continue;
}
sum=sum/4;
flag=0;
memset(vis,0,sizeof(vis));
bfs(1,0,0);
if(flag)
{
printf("yes\n");
}
else
{
printf("no\n");
}
}
return 0;
}
------------------------------------------------
import java.util.Scanner;
public class Main1518 {
static int[]now;
static int flag,m,sum;
public static void main(String[] args) {
Scanner cin=new Scanner(System.in);
while(cin.hasNext()){
int n=cin.nextInt();
while(n-->0){
m=cin.nextInt();
now=new int[m];
sum=0;
for(int i=0;i<m;i++){
now[i]=cin.nextInt();
sum+=now[i];
}
if(sum%4!=0){
System.out.println("no");
continue;
}
int i;
for(i=0;i<m;i++){
if(now[i]>sum/4){
break;
}
}
if(i!=m){
System.out.println("no");
continue;
}
sum=sum/4;
flag=0;
bfs(1,0,0);
if(flag==1){
System.out.println("yes");
}
else{
System.out.println("no");
}
}
}
return;
}
private static void bfs(int i, int j, int k) {
if(i==5){
flag=1;
return;
}
if(j==sum){
bfs(i+1,0,0);
if(flag==1)
return;
}
for(int s=k;s<m;s++){
if(now[s]!=0&&now[s]+j<=sum){
int sk=now[s];
now[s]=0;
bfs(i,sk+j,s+1);
if(flag==1)
return;
now[s]=sk;
}
}
}
}
-------------------------------------------------
通过java和c之间的编写,我发现了java要比c严密很多。例如sum%4==1在c里面可以通过,但是在java里面sun%4!=0,因为要考虑到全面,只要不能整除就不能构成正方形。