1. 程式人生 > >Traveling on the Axis (ACM-ICPC青島網路賽)

Traveling on the Axis (ACM-ICPC青島網路賽)

BaoBao is taking a walk in the interval [0,n] on the number axis, but he is not free to move, as at every point (i−0.5) for all i∈[1,n], where i is an integer, stands a traffic light of type t ​i ​​ (t ​i ​​ ∈{0,1}).

BaoBao decides to begin his walk from point p and end his walk at point q (both p and q are integers, and p

/*題目大意:Bao在數軸的間隔[0,n]上散步,但他不能自由移動,[1,n]處有n個路燈,
1代表綠燈可以行走,0代表紅燈不能行走,紅綠燈每過1秒都會改變(1變0,0變1),
求出走所有路徑所用的時間(只能從前往後走,可以從0開始走,但路燈從1處才開始有)

解題思路:
例: 1 1 0 1 0
從0:1 3 4 5 6
從1:  1 2 3 4 除第一個數其他都為上一行數減二
從2:    2 3 4 除第一個數其他都和上一行數一樣
從3:      1 2 所有數其他都為上一行數減二
從4:        2 除第一個數其他都都和上一行數一樣
從中可以找出規律,若與前面的燈一樣,則需要經過兩秒,若不一樣則只需一秒,
因為經過前面一定是綠燈,那此處本來是紅燈,經過一秒剛好變成綠燈
*/
#include<iostream> #include<cstdio> #include<cstring> using namespace std; int a[100005]; char s[100005]; int main() { long long sum;//一定要用long long int n, i, j, t; scanf("%d", &t); while(t--) { scanf("%s", &s);//先以字串形式輸入 n = strlen(s); long
long ans = 0, maxn = 0; for(i = 0; i < n; i++) { a[i] = s[i] - '0';//變為數字形式 if(i == 0) { if(a[i] == 0)//如果開頭為0,則需要等一秒再走,經過他共需兩秒 maxn = 2; else//如果開頭為1,則直接走,只需一秒 maxn = 1; } else { if(a[i] == a[i-1]) maxn += 2; else maxn += 1; //maxn表示從0點出發到達i點的時間 } ans += maxn;//算出從0出發走完全過程的時間 } sum = ans;//sum記錄所有路程總時間 int m = n; //下面是根據我寫的例子所找出的規律 for(i = 1; i < n; i++) { if(a[i-1] == 1 && a[i] == 1) { ans = ans - ((m-1) * 2 + 1); } else if(a[i-1] == 1 && a[i] == 0) { ans = ans - 1; } else if(a[i-1] == 0 && a[i] == 1) { ans = ans - (m * 2); } else if(a[i-1] == 0 && a[i] == 0) { ans = ans - (m * 2); } sum += ans; m--; } printf("%lld\n", sum); } return 0; }