与这些代码的性能有关?一个非常快,另一个超过了时间限制
Related with the performance of these codes? One being very fast and other exceeding the Time limit
我在Codechef上遇到了一个问题!嗯,我能够为它制定一个动态编程解决方案,但它只通过了三分之一的测试用例!
当我遇到一个作者的解决方案时,它和我的非常接近!但即使在尝试了(对我的代码进行了所有可能的逻辑更改)之后,我的解决方案也不起作用,也没有通过测试用例!
我的代码(我必须把它作为一个整体发布,因为我不能简单地理解为什么它这么慢!)
#include<bits/stdc++.h>
using namespace std;
int A[5001];
long long DP[5001][5001];
int T,i,j;
int N,K,l;
int main()
{
scanf("%d",&T);
for(;T--;)
{
scanf("%d%d",&N,&K);
for(i=1;i<=N;i++)
scanf("%d",&A[i]);
// for(i=1;i<=K;i++)
// DP[0][i]=INT_MIN;
for(i=0;i<=N;i++)
for(j=1;j<=K;j++)
DP[i][j]=INT_MIN;
for(i=1;i<=N;i++)
{
int temp=0,low;
for(l=i;l>=1;l--)
{
if(temp|A[l] >temp)
{
low=min(l,K);
temp|=A[l];
for(j=1;j<=low;j++)
DP[i][j]=max(DP[l-1][j-1]+temp,DP[i][j]);
}
}
}
printf("%lldn",DP[N][K]);
}
return 0;
}
我试过什么?
将cin-cout与ios::sync_with_stdio(0);
一起使用,而不是使用scanf-printf。使用memset清除DP数组!声明变量,全局而不是局部(它们是我的代码和作者的代码之间的区别)。然后我尝试提交作者的代码,只是为了检查它是否真的有效。确实如此!
最初我有一个Memoize版本,我把它改成了DP,但它仍然不起作用。
我使用for循环只是因为就性能而言,它们被认为比while循环更好!
注意:我也可以将INT_MIN的设置更改为0,我也尝试过。不起作用!
作者的解决方案
#include <bits/stdc++.h>
#define rf freopen("in.in", "r", stdin)
#define wf freopen("out.out", "w", stdout)
#define rep(i, s, n) for(int i=int(s); i<=int(n); ++i)
using namespace std;
const int mx = 1e5+10;
int n, t, k;
int a[mx];
long long calc[5111][5111];
int main()
{
//rf;// wf;
scanf("%d", &t);
while(t--)
{
memset(calc, 0, sizeof calc);
scanf("%d %d", &n, &k);
rep(i, 1, n)
scanf("%d", &a[i]);
rep(i, 1, n)
{
int cur = 0, next = 0;
for(int j = i; j; --j)
{
next = cur | a[j];
if(cur == next)
continue;
rep(l, 1, min(k-1, j-1))
calc[i][l+1] = max(calc[j-1][l]+next, calc[i][l+1]);
cur = next;
}
calc[i][1] = cur;
}
printf("%lldn", calc[n][k]);
}
return 0;
}
由于声誉原因,我无法发布图像,但我的解决方案超过了第二和第三个子任务的每个测试用例。
以防万一,如果你需要问题陈述问题(代码厨师),但我认为在比较这些代码时不需要它!
注意操作员优先级:
temp|A[l] >temp
将被评估为
temp|(A[l] >temp)
相关文章:
- 我从int x[3]得到的一个非常奇怪的输出;
- 一个非常简单的win32套接字代码,但工作错误
- 超过CPU时间限制:当MPI_Sent一个非常大的int*时
- 无法使用crfsuite的C++ API编译一个非常简单的Tagger示例
- 维护/维持两个代码集的风险,一个用于 CPU,一个用于 GPU,需要执行非常相似的功能
- C++中一个非常简单的枚举类错误
- 新的一个一维阵列,非常大,例如60000*60000
- 一个关于在函数中运行未调用语句的非常奇怪的错误
- 我在内存泄漏和字符串方面遇到了一个非常奇怪的问题
- 我正在写一个非常简单的字母评分系统,if语句是最有效的吗?
- 我刚刚创建了一个非常快速的素数排序方法.如何改进?
- 我的调试器说我有一个隔离错误错误,但无法告诉我在哪里,在非常特殊的情况下发生
- 在64位系统上创建一个非常大的数组的缺点是什么
- (c++)代码中一个非常奇怪的问题
- 打印出一个非常小的浮点数
- C++:C字符串、指针和一个非常有趣的while循环
- 在 matlab 中编写一个非常基本的 mex 函数
- 在C 中编写一个非常简单的事件类
- 如何取一个非常大的数的根
- 在使用Qt Creator创建一个非常简单的项目时,在Qt中遇到"segmentation fault"