AOJ 740 summation, aoj740 summation
Link: http://icpc.ahu.edu.cn/OJ/Problem.aspx? Id = 740 Description for positive integers n, k, we define such a function f, which satisfies the following rules:
F (n, k = 1) =-1 + 2-3 + 4-5 + 6... n
F (n, k = 2) =-1-2 + 3 + 4-5-6... n
F (n, k = 3) =-1-2-3 + 4 + 5 + 6... n
F (n, k = 4) =-1-2-3-4 + 5 + 6 + 7 + 8... n
Given n and k, your task is to calculate the value of f (n, k.
Input is an integer T, indicating that T groups of data exist.
Next, the data in each group is n and k (1 <= n, k <= 100000000)
Output prints the value of f (n, k). Each Output occupies a single row.
Sample Input
31 12 13 1
Sample Output
-11-2
Source Anhui Province 2015 "Jingsheng Cup" College Student Program Design Competition
Source: http://icpc.ahu.edu.cn/OJ/Problem.aspx? Id = 740
Simple question:
-
Find the rule. The cycle size is k * k and the length is 2 * k.
-
Although this solution can be used in a low-key manner, the consumed time is still close to 1 s ~
1 #include<iostream> 2 using namespace std; 3 4 int main() 5 { 6 long long t; 7 cin>>t; 8 while(t--) 9 {10 long long n,k,l;11 while(cin>>n>>k)12 {13 l=n/(2*k);14 long long sum=l*k*k;15 long long s=k;16 for(long long i=l*2*k+1;i<=n;i++)17 {18 if(s!=0)19 {20 sum-=i;21 s--;22 }23 else24 sum+=i;25 } 26 cout<<sum<<endl;27 } 28 }29 return 0;30 }