poj 3187 이전 Digit Sums (dfs 검색)
FJ and his cows enjoy playing a mental game. They write down the numbers from 1 to N (1 <= N <= 10) in a certain order and then sum adjacent numbers to produce a new list with one fewer number. They repeat this until only a single number is left. For example, one instance of the game (when N=4) might go like this:
3 1 2 4
4 3 6
7 9
16
Behind FJ's back, the cows have started playing a more difficult game, in which they try to determine the starting sequence from only the final total and the number N. Unfortunately, the game is a bit above FJ's mental arithmetic capabilities. Write a program to help FJ play the game and keep up with the cows.
입력
Line 1: Two space-separated integers: N and the final sum.
출력
Line 1: An ordering of the integers 1..N that leads to the given sum. If there are multiple solutions, choose the one that is lexicographically least, i.e., that puts smaller numbers first.
샘플 입력
4 16
샘플 출력
3 1 2 4
제시 하 다.
Explanation of the sample:
There are other possible sequences, such as 3 2 1 4, but 3 1 2 4 is the lexicographically smallest.
이 문제 의 난점 은 주로 정점 의 마지막 층 의 숫자의 관 계 를 구한다.처음에는 저도 몰 랐 는데 나중에 봤 어 요.http://blog.sina.com.cn/s/blog_6635898a 0100 kko 3. html 이 문 제 를 풀 어야 원래 sum = C (0, n - 1) * num [0] + C (1, n - 1) * num [1] + '+ C (n - 1, n - 1) * num [n - 1] 을 알 수 있 습 니 다. 그 다음 에 검색 num 배열 입 니 다.
#include <iostream>
#include <stdio.h>
using namespace std;
int n,sum,c[11],dp[11];int vis[11];
bool flag;
int fond_c(int a,int b)// C(a,b)
{
int ans=1;int m=b;
for(int i=1;i<=a;i++)
{
ans=ans*m/i;
m--;
}
return ans;
}
void dfs(int deep,int val)
{
if(val>sum)return ;
if(deep==n)
{
if(val==sum)
{
for(int i=0;i<n;i++)
printf("%d ",dp[i]);
flag=true;
}
return ;
}
for(int i=1;i<=n&&!flag;i++)
{
if(!vis[i])
{
dp[deep]=i;
vis[i]=1;
dfs(deep+1,val+i*c[deep]);
vis[i]=0;
}
}
}
int main()
{
scanf("%d%d",&n,&sum);
for(int i=0;i<=n-1;i++)
{
c[i]=fond_c(i,n-1);
}
dfs(0,0);
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.