Description
Input
Output
Sample Input
7 10000 -1
Sample Output
20 18658
题目大意 很简单 这里 就不多说 啦~
但是要 注意 的是,此题采用一般的在线方法 ,很容易TLE,所以 要采用离线做法,即先把数组a[1000000]初始化。
具体讲解见代码:
#include <iostream> #include <cstdio> #include <algorithm> #include <cstring> #include <string> #include <cmath> #include <map> using namespace std; int a[1000000]; int main() { map<int , int> mymap; //定义map,意在 判断 数据 是否出现过,具体运用如下: mymap.clear(); a[0]=0; a[1]=1; a[2]=3; mymap[a[0]] =1; // 把出现过的值统统 标记为 1 mymap[a[1]] =1; mymap[a[2]] =1; int i; for(i=3; i<=500006; i++) { a[i]=a[i-1]-i; if(mymap.find(a[i])!=mymap.end()||a[i]<=0) { a[i]=a[i-1]+i; } mymap[a[i]] = 1; } int k; while (scanf("%d",&k)!=EOF) { if(k==-1) break; printf("%d\n",a[k]); // 初始化数组a[]后,直接输出a[k] } }