fork download
  1. #include<bits/stdc++.h>
  2.  
  3. // #include <ext/pb_ds/assoc_container.hpp>
  4. // #include <ext/pb_ds/tree_policy.hpp>
  5. #include<unordered_map>
  6. #include<unordered_set>
  7. #include<stdio.h>
  8. #include<stdlib.h>
  9. typedef long long ll;
  10. #define pi 3.1415926535
  11. #define mod 1000000007 //change when needed
  12.  
  13. using namespace std;
  14. // using namespace __gnu_pbds;
  15. template <typename T>
  16. T InvMod(T a,T b,T &x,T &y)
  17. {
  18. if(a==0)
  19. {
  20. x=0;
  21. y=1;
  22. return b;
  23. }
  24. T x1,y1;
  25. T g=InvMod(b%a,a,x1,y1);
  26. x=y1-(b/a)*x1;
  27. y=x1;
  28. return g;
  29. }
  30. ll fact(ll n)
  31. {
  32. if(n==1)
  33. return 1;
  34. return (n%mod*fact(n-1)%mod)%mod;
  35. }
  36. void sieve(vector<int> &v)
  37. {
  38. bool arr[1000004];
  39. memset(arr,true,sizeof arr);
  40. // memset(arr,0,sizeof arr);
  41. for(int i=2;i*i<=1000002;i++)
  42. {
  43. if(arr[i]==true)
  44. {
  45. v.push_back(i);
  46. for(int j=i*i;j<=1000002;j+=i)
  47. {
  48. arr[j]=false;
  49. }
  50. }
  51. }
  52. }
  53. bool cmp(pair<int,int> a,pair<int,int> b)
  54. {
  55. return a.first>b.first;
  56. }
  57. int main()
  58. {
  59. ios_base::sync_with_stdio();
  60. cin.tie(NULL);
  61. int t;
  62. cin>>t;
  63. while(t--)
  64. {
  65. ll n;
  66. cin>>n;
  67. pair<ll,ll> arr[n];
  68. ll tmp=0;
  69. for(int i=0;i<n;i++)
  70. {
  71. cin>>arr[i].first>>arr[i].second;
  72. if(i>0)
  73. {
  74. tmp+=max(0ll,arr[i].first-arr[i-1].second);
  75. }
  76. }
  77. tmp+=max(0ll,arr[n%n].first-arr[n-1].second);
  78. ll ans=1e18;
  79. for(int i=0;i<n;i++)
  80. {
  81. tmp-=max(0ll,arr[(n+i-1)%n].first-arr[(n+i-2)%n].second);
  82. ans=min(ans,tmp+arr[(i+n-1)%n].first);
  83. tmp+=max(0ll,arr[(n+i-1)%n].first-arr[(n+i-2)%n].second);
  84. }
  85. cout<<ans<<"\n";
  86. }
  87. }
Success #stdin #stdout 0s 4368KB
stdin
Standard input is empty
stdout
Standard output is empty