1.某些整數能分解成若干個連續整數的和的形式,例如
15 = 1 + 2+3+4+515 = 4 + 5 + 6
15 = 7 + 8
某些整數不能分解爲連續整數的和,例如:16
輸入:一個整數N(N <= 10000)
輸出:整數N對應的所有分解組合,按照每個分解中的最小整數從小到大輸出,每個分解佔一行,每個數字之間有一個空格(每行最後保留一個空格);如果沒有任何分解組合,則輸出NONE。
#include "stdafx.h"
#include <iostream>
#include <string>
#include "math.h"
#include "stdio.h"
#include "string.h"
#include "ctype.h"
#include <vector>
#include <queue>
#include <map>
#include <algorithm>
using namespace std;
int main(int argc, char* argv[])
{
int n,flag=0;
scanf("%d",&n);
for(int i=1;i<=n/2;i++){
for(int j=i+1;j<=n-i;j++){
if(n==(i+j)*(j-i+1)/2){
flag=1;
printf("%d=",n);
for(int k=i;k<j;k++)
printf("%d+",k);
printf("%d\n",k);
}
}
}
if(!flag) printf("none");
return 0;
}
2.小島面積
1 1 1 1 1 1
1 1 0 0 0 1
1 0 0 0 1 0
1 1 0 1 1 1
0 1 0 1 0 0
1 1 1 1 1 1
上面矩陣的中的1代表海岸線,0代表小島。求小島面積(即被1中包圍的0的個數)。注意:僅求這樣的0,該0所在行中被兩個1包圍,該0所在列中被兩個1包圍。
輸入:
第一行輸入一個整數N,表示輸入方陣的維數
輸入一個N維方陣
輸出:
小島面積
樣例輸入:
6
1 1 1 1 1 1
1 1 0 0 0 1
1 0 0 0 1 0
1 1 0 1 1 1
0 1 0 1 0 0
1 1 1 1 1 1
樣例輸出:
8
理解題目本身意思,可以發現對於矩陣中的0是否屬於內陸,取決於該0所處的行和列上,如果0滿足,如下條件則O爲內陸,否則不是。
Ø 0所在的行,0的左邊和右邊必須有1
Ø 0所在的列,0的上面和下面必須有1
所以,解題思路就是,遍歷所有的行和列,記錄改行或列,最左面和最右面(或者最上面和最下面)1的座標,然後當遇到0,判斷是否處於記錄的值的中間,是,則是內陸,面積加1,否則不加。
#include "stdafx.h"
#include <iostream>
#include <string>
#include "math.h"
#include "stdio.h"
#include "string.h"
#include "ctype.h"
#include <vector>
#include <queue>
#include <map>
#include <algorithm>
using namespace std;
/*
1 1 1 1 1 1
1 1 0 0 0 1
1 0 0 0 1 0
1 1 0 1 1 1
0 1 0 1 0 0
1 1 1 1 1 1
*/
int main(int argc, char* argv[])
{
int maze[100][100];
int flag[4][100]; // 0--left 1--right 2--top 3--bottom
int n,i,j;
int sum=0;
scanf("%d",&n);
memset(flag,-1,400*sizeof(int));
for(i=0;i<n;i++){
for(j=0;j<n;j++){
scanf("%d",&maze[i][j]);
if(maze[i][j]==1){
if(flag[0][i]==-1) flag[0][i]=j;
if(flag[2][j]==-1) flag[2][j]=i;
flag[1][i]=j;
flag[3][j]=i;
}
}
}
for(i=0;i<4;i++){
for(j=0;j<n;j++){
printf("%d ",flag[i][j]);
}
printf("\n");
}
for(i=0;i<n;i++){
for(j=0;j<n;j++){
if(maze[i][j]==0&&flag[0][i]<j&&flag[1][i]>j&&flag[2][j]<i&&flag[3][j]>i) sum++;
}
}
printf("%d",sum);
return 0;
}
3.輸入一行C語言代碼,查找關鍵字if,while,for並按照出現順序輸出。輸出格式:
關鍵字:位置
關鍵字:位置
#include "stdafx.h"
#include <iostream>
#include <string>
#include "math.h"
#include "stdio.h"
#include "string.h"
#include "ctype.h"
#include <vector>
#include <queue>
#include <map>
#include <algorithm>
using namespace std;
int main(int argc, char* argv[])
{
char str[301];
int i,j;
int len;
int flag=0;;
gets(str);
len=strlen(str);
for(i=0;i<len;i++){
if(str[i]=='"') flag=1-flag;
if(flag==1) continue;
switch (str[i]){
case 'i':
if(i<len-1&&str[i+1]=='f'){
printf("if:%d\n",i);
}
break;
case 'w':
if(i<len-4&&str[i+1]=='h'&&str[i+2]=='i'&&str[i+3]=='l'&&str[i+4]=='e'){
printf("while:%d\n",i);
}
break;
case 'f':
if(i<len-2&&str[i+1]=='o'&&str[i+2]=='r'){
printf("for:%d\n",i);
}
break;
}
}
return 0;
}