책보면서 열심히 문제풀이를 하는데, 막혔습니다
아래 코드에 보시면 reconstruct 함수 내에 assert(choose != -1);을 넣었는데, 제출해보면 assert에 의해서 중단됩니다. 그런데 왜 choose가 바뀌지 않는지/바뀌지 않은 choose에 접근하는지 도통 모르겠습니다. 도와주세요!!
코드
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
#include<cmath>
#include<cassert>
using namespace std;
int m, q;// m:단어의 수, q:처리할 문장의 수
int n;//문장을 구성하는 단어의 갯수
double B[501]; // i단어의 문장처음출현확률
double T[501][501]; // i단어뒤에 j단어가 올 확률
double M[501][501]; // i단어를 j단어로 분류할 확률
string words[501]; // 인식가능한 단어들
int sentence[101];
int choice[101][502]; // -1 로 초기화
double cache[101][502]; // 1.0으로 초기화
double recSolve(int curpos, int prevword)
{
if (curpos == n)
{
return 0;
}
double& ret = cache[curpos][prevword];
int& choose = choice[curpos][prevword];
if (ret != 1.0) return ret;
ret = -1e200; //log(0) = 음의무한대
if (curpos == 0)
{
for (int thisword = 0; thisword < m; thisword++)
{
double cand = B[sentence[curpos]] + M[thisword][sentence[curpos]]
+ recSolve(curpos + 1, thisword);
if (ret < cand)
{
ret = cand;
choose = thisword;
}
}
}
else{
for (int thisword = 0; thisword < m; thisword++)
{
double cand = T[prevword][thisword] + M[thisword][sentence[curpos]]
+ recSolve(curpos + 1, thisword);
if (ret < cand)
{
ret = cand;
choose = thisword;
}
}
}
return ret;
}
string reconstruct(int curpos, int prevword){
int choose = choice[curpos][prevword];
assert(choose != -1);
string ret = words[choose];
if (curpos < n - 1){
ret = ret + " " + reconstruct(curpos + 1, choose);
}
return ret;
}
string Solve()
{
recSolve(0, 0);
return reconstruct(0, 0);;
}
int main()
{
cin >> m >> q;
for (int i = 0; i < m; i++)
{
cin >> words[i];
}
//B입력
for (int i = 0; i < m; i++)
{
double t;
cin >> t;
B[i] = log(t);
}
//T입력
for (int i = 0; i < m; i++)
{
for (int j = 0; j < m; j++)
{
double t;
cin >> t;
T[i][j] = log(t);
}
}
//M입력
for (int i = 0; i < m; i++)
{
for (int j = 0; j < m; j++)
{
double t;
cin >> t;
M[i][j] = log(t);
}
}
for (int i = 0; i < q; i++)
{
//캐시,choice초기화
for (int i = 0; i < 101; i++)
{
for (int j = 0; j < 502; j++)
{
cache[i][j] = 1.0;
choice[i][j] = -1;
}
}
cin >> n;
for (int j = 0; j < n; j++)
{
string inputword;
cin >> inputword;
for (int k = 0; k < m; k++)
{
if (inputword == words[k])
{
sentence[j] = k;
break;
}
}
}
cout << Solve() << endl;
}
return 0;
}
takun612
질문 내용
책보면서 열심히 문제풀이를 하는데, 막혔습니다
아래 코드에 보시면 reconstruct 함수 내에 assert(choose != -1);을 넣었는데, 제출해보면 assert에 의해서 중단됩니다. 그런데 왜 choose가 바뀌지 않는지/바뀌지 않은 choose에 접근하는지 도통 모르겠습니다. 도와주세요!!
코드
9년 전