题目链接:http://acm.tju.edu.cn/toj/showp3474.html
题目大意:见原题图示。
思路:(1)简单递归:这个容易;(2) DFS(待理解) 转自:http://www.cppblog.com/zhunki/archive/2010/07/30/121659.html
代码:
(1)递归:
#include<iostream>
using namespace std;
int a[2201],i;
int get(int x,int y)
{
//cout<<x<<" "<<y<<endl;
if(x+1==y)return a[x]*a[y];
if(x==y) return 0;
int tmp=(y+x)/2;
return get(x,tmp)+get(tmp+1,y);
}
int main()
{
int n;
cin>>n;
for(i=1;i<=n;i++)
a[i]=i;
cout<<get(1,n)<<endl;
return 0;
}
(2)DFS: 理解不够透彻!求指教
#include<iostream>
using namespace std;
int stack[2421100][3];
int main(){
int n;
scanf("%d",&n);
int top=-1,sum=0;
stack[++top][0]=1;
stack[top][1]=n;
stack[top][2]=2;//left:no,right:no
while(top>=0){
if(stack[top][1]-stack[top][0]==0){
top--;
}else if(stack[top][1]-stack[top][0]==1){
sum+=stack[top][1]*stack[top][0];
top--;
}else if(stack[top][2]==0){
top--;
}else if(stack[top][2]==1){
top++;
stack[top][0]=(stack[top-1][0]+stack[top-1][1])/2+1;
stack[top][1]=stack[top-1][1];
stack[top-1][2]=0;
stack[top][2]=2;
}else{
top++;
stack[top][0]=stack[top-1][0];
stack[top][1]=(stack[top-1][0]+stack[top-1][1])/2;
stack[top-1][2]=1;
stack[top][2]=2;
}
}
printf("%d\n",sum);
return 0;
}